【问题标题】:Get properties with attribute获取带有属性的属性
【发布时间】:2013-06-19 05:30:46
【问题描述】:

我正在尝试解决如何从类中获取所需属性的问题。我可以使用GetPropertiesForSerialization 之类的功能,但我想使用Attributes。我的想法是某些类属性将具有属性

class C{
  [MyAttribute(1,picture)]
  private string picture = "my.jpg";
  [MyAttribute(2,Name)]
  public string Name= "myName";
}

现在我想从其他班级获取属性

private void PrintAttributes(){
  //Get list or other container with attibutes
  var c = new C();
  foreach( var item in C.GetMyAttributes()){
    Console.WriteLine(item);
  }
}

我知道如何获取函数等的属性,但不知道如何在不知道属性名称和保护(公共/私有)的情况下获取所有这些属性。

【问题讨论】:

  • 您是否要获取所有属性名称?

标签: c#


【解决方案1】:

您可以使用反射 myObject.GetType().GetProperties() 获取所有属性,然后检查每个属性的属性。

【讨论】:

  • 好,我试试这个“蛮力”。
  • 如果您要序列化大量相同类型的对象,您可以对每种类型执行一次并缓存结果。
  • 我试过了,item.GetCustomAttribute(typeof(MyAttribute), true); 但没有任何发现。该类实现接口并存储在ÌnterfaceI class; class.GetType...中。但没有找到具有属性的属性
  • 对不起,我的错误......只需要 GetProperties 和 GetField ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2015-01-29
  • 2014-01-17
  • 1970-01-01
相关资源
最近更新 更多