通过参数对属性强制接口

时间:2018-12-06 20:18:57

标签: c#

我们需要一个自定义属性,它需要一个类型。 例如

[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public class MyCustomAttribute : Attribute
{
    public Type BindingInterface { get; }
    public MyCustomAttribute(Type bindingInterface)
    {
        this.BindingInterface = bindingInterface;
    }
}

我想做的是确保用户已实现使用属性的接口。用户也有可能通过层次结构来实现它,但是我需要检查应用属性的位置。

例如,

public abstract class SomeBase : ISomeInterface
{
}

[MyCustomAttribute(typeof(ISomeInterface))]
public class Implementation : SomeBase
{
}

但是,如果用户未实现该接口,则我要编译错误。这可能吗?

[MyCustomAttribute(typeof(ISomeInterface))]
public class IncorrectUsageAsItDoesntHaveTheBindingInterface
{
}

[编辑] 只是想指出,此关闭的原因是不合法的。由于多种原因,它与链接的问题不同。 这是针对一个类而不是一个属性。该属性可以访问绑定类型,并且不尝试强制使用原始类型。这些是重要的差异。我之所以保持关闭完全是因为评论确实回答了我的问题。特别是LasseVågsætherKarlsen的评论提供了一条路径。

0 个答案:

没有答案