3
我想将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
}
正如我怀疑,非常感谢您的答案。我想知道我是否在这里成为XY问题的受害者;也许我的整个方法都是关闭的。再次感谢。 –