0

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

每当我创建“MyClass”的新实例或从 IMyInterface 继承的任何其他类时,我希望所有用 [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;
    }
}
4

2 回答 2

0

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

于 2010-03-25T13:11:12.820 回答
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);
      }
    }
  }
}

免责声明:代码可能无法编译,我只是从头顶写的。

于 2010-03-25T11:18:46.413 回答