基于自定义属性创建对象

时间:2013-01-07 16:47:03

标签: c# attributes abstract-class

我有一个抽象类

public abstract class BaseClass
{
    public abstract void CreateGraph(){}
}

[CustomAttribute(Property1 = value , Property2 = value2)]
public class Graph1 : BaseClass
{
 public override void CreateGraph()
     {
       //implementation
     }
}

如何使用Graph1属性值创建CustomAttribute的对象。 这是创建对象的好方法。

3 个答案:

答案 0 :(得分:0)

不,这不是一个好方法,因为在.NET中,必须在编译时知道属性值。例如,示例中的valuevalue2只能是常量值,这极大地限制了设置值的可能性。

答案 1 :(得分:0)

不需要为此使用属性,只需遵循常见的面向对象设计。查看Factory design pattern

答案 2 :(得分:0)

如果需要自定义属性,则应定义继承自System.Attribute的类。实际上,如果在System.AttributeUsage中将AllowMultiple参数设置为true,则可以使用不同的值多次使用自定义属性。

你可以check that here

然而你不需要那个“创造对象”,我不确定通过“好方法”看到你的意思。如上所述,你应该看看GoF  根据您的需要设计最佳实践模式。