【问题标题】:How to define a constraint on class type if It has custom attribute?如果它具有自定义属性,如何定义对类类型的约束?
【发布时间】:2011-05-08 09:24:32
【问题描述】:

如果类有特定的自定义属性,有什么方法可以强制类实现接口?

如果具有特定属性的类没有实现特定接口,我想出现编译时错误。

[myAttrib]
public MyClass:IMyInterface
{

}

如果 myClass 不是 typeof(IMyInterface) ,我会在编译时出错。

谢谢,

【问题讨论】:

  • 您可以从接口创建一个抽象类驱动,并从该抽象类获取最终类驱动。

标签: c#-4.0 custom-attributes compile-time-constant


【解决方案1】:

如果是属性,您可以创建一个继承接口的抽象类,并从该抽象类获取您的最终类驱动。

看看

public interface Test
    {
        string Name { get; set; }
    }

    public abstract class Test1 : Test
    {
        public abstract string Name { get; set; }
    }

    public class Test2 : Test1
    {

    }

对于你可以做的自定义属性

public class Alias : System.Attribute
    {
    string[] _types;

    public Alias(params string[] types)
    {
        this.Types = types;
    }
    public Alias()
    {
        this.Types = null;
    }

    public string[] Types
    {
        get { return _types; }
        set { _types = value; }
    }
  }

    public interface Test
    {
        Alias Attrib{ get;}
    }

    public abstract class Test1 : Test
    {
        public abstract Alias Attrib { get; }
    }

    public class Test2 : Test1
    {

    }

希望我能回答你的问题。

【讨论】:

  • 嗨,阿卜杜勒,感谢您的回复,但您似乎没有很好地理解我的问题,我说的是 [自定义属性] 而不是属性
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 2010-10-12
  • 2018-10-05
  • 2019-04-08
  • 1970-01-01
相关资源
最近更新 更多