簡體   English   中英

C# 反射使用自定義屬性獲取屬性內的所有屬性信息

[英]C# reflection get all property information inside the proerperties with custom attribute

我正在編寫一種方法,用於從具有自定義屬性的 object(包括其自身的屬性)中提取所有屬性。 例如

  public class SomeModel
{

    [Custom]
    public string Name { get; set; }


    public string TestData { get; set; }

    [Custom]
    public string Surname { get; set; }

   public  InnerModel InnerModel { get; set; }
}

和內 Model:

  public class InnerModel
{
    public string Id { get; set; } = "TestID";

    [Custom]
    public string Year { get; set; }

    public ThirdObject HidedObject { get; set; }
}

第三個:

 public class ThirdObject
{
    [Custom]
    public string  HidedName { get; set; }
}

我需要找到所有具有“自定義”屬性的屬性。 測試:

SomeModel model = new SomeModel()
        {
            Name = "farid",
            Surname = "Ismayilzada",
            TestData = "Test" ,
            InnerModel = new InnerModel() { Year ="2022" , HidedObject= New ThirdObject{ HidedName="Secret"}}
        };

我需要寫方法

GetMyProperties(model) => List<PropInf>()
[PropertyName= Name,Value=Farid ,Route="Name" ]
[PropertyName= Surname,Value=Ismayilzada,Route="Surname" ]
[PropertyName= Year,Value=2022,Route="InnerModel.Year" ]
[PropertyName= HidedName,Value=Secret,Route="InnerModel.HidedObject.HidedName" ]

如何獲取這些信息?

你可以寫一個這樣的方法:

private static IEnumerable<PropInfo> GetPropertiesInfo(object obj, string route = "")
{
    List<PropInfo> results = new List<PropInfo>();

    // You can filter wich property you want https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo?view=net-6.0
    var objectProperties = obj.GetType().GetProperties().Where(p => p.CanRead);
    foreach (var property in objectProperties) 
    {
        var value = property.GetValue(obj);

        if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
        {
            results.AddRange(GetPropertiesInfo(value, route + property.Name + "."));
        }
        else
        {
            // Check if the property has the Custom Attribute
            var customAttributes = property.GetCustomAttributes<CustomAttribute>();
            if (!customAttributes.Any())
                continue;
            // You can set a method in your Attribute : customAttributes.First().CheckIfNeedToStoreProperty(obj);

            results.Add(new PropInfo()
            {
                PropertyName = property.Name,
                Value = value,
                Route = route + property.Name
            });
        }

    }

    return results;
}

public class PropInfo
{
    public string PropertyName { get; set; }
    public object Value { get; set; }
    public string Route { get; set; }
}

public class CustomAttribute : Attribute
{
    public bool CheckIfNeedToStoreProperty(object obj)
    {
        return true;
    }
}

暫無
暫無

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

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