填充用属性修饰的属性

时间:2010-03-25 11:09:18

标签: c# attributes structuremap inject

是否有任何框架可以帮助我:(想想也许StructureMap可以帮助我)

每当我创建一个新的“MyClass”实例或从IMyInterface继承的任何其他类时,我希望使用属性中的属性Name从数据库或其他一些数据存储中填充用[MyPropertyAttribute]修饰的所有属性。

public class MyClass : IMyInterface
{
    [MyPropertyAttribute("foo")]
    public string Foo { get; set; }
}

[AttributeUsage(AttributeTargets.Property)]
public sealed class MyPropertyAttribute : System.Attribute
{
    public string Name
    {
        get;
        private set;
    }

    public MyPropertyAttribute(string name)
    {
        Name = name;
    }
}

2 个答案:

答案 0 :(得分:0)

改为使用抽象类(如果你坚持使用接口,则使用工厂模式)。

使用抽象类,您可以在默认构造函数中进行必要的填充,并进行一些反射。

类似的东西:

abstract class Base
{
  protected Base()
  {
    var actualtype = GetType();
    foreach (var pi in actualtype.GetProperties())
    {
      foreach (var attr in pi.GetCustomAttributes(
         typeof(MyPropertyAttribute), false))
      {
        var data = GetData(attr.Name); // get data
        pi.SetValue(this, data, null);
      }
    }
  }
}

免责声明:代码可能无法编译,我只是从头脑中写下来。

答案 1 :(得分:0)

从codeplex检查以下框架: http://www.codeplex.com/AutoMapper用于映射和 http://fasterflect.codeplex.com/用于快速反射以收集属性和设定值或获取值。

相关问题