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

时间:2014-09-22 20:58:05

标签: c# reflection

我有这个:

public class Test{
   public string Name{get;set;}
}

var instance = new Test();


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

我希望在我的课程中有一些后备功能,所以在我们的情况下,如果没有名为" Id"的属性,它将调用我的后备功能并处理它。

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

2 个答案:

答案 0 :(得分:0)

之前如何设置回退函数,(我假设您可以在开始调用可能不存在的名称之前执行此操作),然后在可疑属性名称的情况下测试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());

答案 1 :(得分:0)

您可以使用扩展方法执行此操作:

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
相关问题