2017-04-05 142 views
3

我想將Type參數傳遞給構造函數。這個構造函數屬於一個屬性。在方法/構造函數中限制「類型」參數

這很簡單。但是,我怎樣才能將這個Type參數約束到一個特定類的子類?

所以我有一個父類ParentClass和兩個子類MyChildClass : ParentClassMyOtherChildClass : ParentClass

我的屬性是這樣的:

public class AssociatedTypeAttribute : Attribute 
{ 
    private readonly Type _associatedType; 

    public Type AssociatedType => _associatedType; 

    public AssociatedTypeAttribute(Type associatedType) 
    { 
     if (!associatedType.IsSubclassOf(typeof(ParentClass))) 
      throw new ArgumentException($"Specified type must be a {nameof(Parentclass)}, {associatedType.Name} is not."); 

     _associatedType = associatedType; 
    } 
} 

這工作,並在運行時,如果該類型不是ParentClass它會拋出一個異常 - 但運行時爲時已晚。

是否可以添加某種約束?我可以在這裏使用泛型,還是說泛型是超越界限的,因爲它是屬性的構造函數?

注意用法:

public enum MyEnum 
{ 
    [AssociatedType(typeof(MyChildClass))] 
    MyEnumValue, 
    [AssociatedType(typeof(MyOtherChildClass))] 
    MyOtherEnumValue 
} 

回答

1

你不能用Type做到這一點,因爲它不允許使用泛型類擴展Attribute你不能使用泛型。

您擁有的最佳解決方案是運行時檢查,如果目標與預期目標不匹配,則簡單忽略該屬性。

+0

正如我懷疑,非常感謝您的答案。我想知道我是否在這裏成爲XY問題的受害者;也許我的整個方法都是關閉的。再次感謝。 –

相關問題