我希望将一个 Type
参数传递给构造函数。这个构造函数属于一个属性。
这很简单。但是如何限制这个 Type
参数只能是特定类的子类呢?
所以我有一个父类 ParentClass
和两个子类 MyChildClass : ParentClass
和 MyOtherChildClass : 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
}