ganggang7ii 2015-01-27 11:55 采纳率: 100%
浏览 1747
已采纳

泛型如何读取变量?这里这么写肯定是不对的。请问怎么写?

void T GetProp(T entity, string propName)
{
return entity.propName();这里这么写肯定是不对的。请问怎么写?
}

  • 写回答

1条回答 默认 最新

  • FoolRabbit 2015-01-28 00:30
    关注

    通过反射可实现

     public MainWindow()
    {
        InitializeComponent();
    
        Test test = new Test();
        test.Name = "TestABC";
        Console.WriteLine(GetProp(test, "Name"));
    }
    
    public class Test
    {
        public string Name { get; set; }
    }
    
    object GetProp<T>(T entity, string propName)
    {
        PropertyInfo[] props = entity.GetType().GetProperties();
        PropertyInfo prop = props.Where(p => p.Name == propName).FirstOrDefault();
        if (prop == null)
        {
            return null;
        }
        else
        {
            return prop.GetValue(entity, null);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?