限制方法/构造函数中的“类型”参数

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个回答

1

你不能使用Type来完成这个操作,也不能使用泛型,因为不允许使用泛型类来扩展Attribute

你最好的解决办法是进行运行时检查,如果目标与预期不匹配,则简单地忽略该属性。


正如我所猜测的那样,非常感谢您的回答。我想知道我是否正在成为XY问题的受害者;也许我的整个方法都是错误的。再次感谢。 - user1017882

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接