2017-04-05 145 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问题的受害者;也许我的整个方法都是关闭的。再次感谢。 –

相关问题