簡體   English   中英

在運行時使用反射查找通用對象屬性的屬性值

[英]Find generic object property attribute value using reflection at run time

我創建了一個自定義屬性類,用於在將對象導出為CSV格式時控制某些方面。

[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
    public bool Exportable { get; set; }
    public string ExportName{ get; set; }
}

這是我要導出的對象之一的示例:

public class ObjectA
{
    [MyCustom(Exportable = true, ExportColumnName = "Column A")]
    public string PropertyA {get; set; }

    [MyCustom(Exportable = false)]
    public string PropertyB {get; set; }

    public string PropertyC {get; set; }
}

我創建接受通用對象的Export函數。

public void Export<T>(T exportObject)
{
   //I get the property name to use them as header
   var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

   foreach (var property in properties)
   {
      //find the list of attribute of this property.
      var attributes = Attribute.GetCustomAttributes(property, false);

     //if attribute "Exportable" value is false or doesn't exists then continue foreach
     //else continue export logic

   } 
}

我的問題是如何使用反射來查找該屬性是否具有“可導出”屬性,以及該屬性是否為true?

請注意,我可以傳入任何通用對象,在這種情況下,我希望最終導出包含一個包含PropertyA數據的列,並且我的列標題值為“ Column A”

您在正確的道路上,將泡沫體替換為:

var attribute = property.GetCustomAttribute<MyCustomAttribute>();

if(attribute != null)
{
  bool isExportable = attribute.Exportable;
  // rest of the code
}

@Sohaib Jundi給出了很好的答案。 如果出於某種原因決定創建更多自定義屬性,則可以執行以下類似操作:

public void Export<T>(T exportObject)
{
    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (var property in properties)
    {
        var attributes = Attribute.GetCustomAttributes(property, false);

        foreach (var attribute in attributes)
        {
            if (attribute is MyCustomAttribute)
            {
                if (((MyCustomAttribute)attribute).Exportable)
                {

                }
            }

            if (attribute is MyCustomAttribute2)
            {
                if (((MyCustomAttribute2)attribute).AnotherThing)
                {

                }
            }
        }
    }
}

這樣,您可以檢查對象的多個屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM