在c#中使用反射时的属性回退

本文关键字:属性 回退 反射 | 更新日期: 2023-09-27 18:23:54

我有这个:

public class Test{
   public string Name{get;set;}
}
var instance = new Test();

Type t = instance.GetType();
System.Reflection.PropertyInfo propInfo = t.GetProperty("Id");

我想在我的类中有一些回退函数,所以在我们的情况下,当没有名为"Id"的属性时,它会调用我的回退函数并处理它。

最重要的是,当有人调用它时,我可以返回我想要的任何值。

在c#中使用反射时的属性回退

之前设置回退函数(我假设您可以在开始调用可能不存在的名称之前完成此操作),然后在出现可疑属性名称的情况下测试null。

例如:

public class Test
{
    [DefaultValue]
    public string Name { get; set; }
}

        var instance = new Test();
        Type t = instance.GetType();
        // set up your fallback fucntion
        System.Reflection.PropertyInfo fallbackInfo = t.GetProperty("Name");
        //if else on the property lookup
        System.Reflection.PropertyInfo propInfo = t.GetProperty("Id") ?? fallbackInfo;
        // your code here
        Console.WriteLine(propInfo.ToString());

您可以使用扩展方法:

public static class Extensions
{
    public static T GetPropertyValueOrDefault<T>(this Type t, object instnace, string Name, T defaultValue)
    {
        var prop = from p in t.GetProperties() where p.Name.Equals(Name) select p;
        if (prop.Any())
        {
            return (T) prop.First().GetValue(instnace);
        }
        return defaultValue;
    }
}

然后使用它:

var instance = new Test();
instance.Name = "Jane";
Type t = instance.GetType();
string Value = t.GetPropertyValueOrDefault(instance, "Name", "JOHN");
Console.WriteLine(Value);   // Returns Jane
Value = t.GetPropertyValueOrDefault(instance, "Id", "JOHN");
Console.WriteLine(Value);   // Returns JOHN