【发布时间】:2014-09-24 05:16:56
【问题描述】:
我根据on SO here的回答创建了一个扩展方法
public class AcObject
{
public int Id { get; set; }
}
public static Dictionary<string, string> GetValidationList<AcObject, TProperty>(
this AcObject source,
Expression<Func<AcObject, TProperty>> propertyLambda)
{
// Autocomplete here only shows static members for 'source'
// I am expecting to be able to do source.Id
}
谁能向我解释为什么我不能在上述场景中使用source.Id,并建议我在哪里可以找到类似的解决方案?
如果我在 GetValidationList() 方法中设置断点,我可以将鼠标悬停在源代码上并查看实例及其属性...我只是无法在 VS 中使用它。
我的总体目标是能够做到以下几点
public class AcObject
{
public int Id { get; set; }
public string Type { get; set; }
}
public class OtherObject : AcObject
{
public string AssetTag { get; set; }
}
// somewhere else in code
AcObject myObject = new AcObject();
myObject.GetValidationList(a => a.Type);
// Along with using the type that inherits it
OtherObject myOtherObject = new OtherObject();
myOtherObject.GetValidationList(a => a.Type);
// In some kind of extension method lambda magic
{
Console.WriteLine(source.Id);
}
编辑 - 更新以包括它在基类以及继承它的那些上工作的要求。
【问题讨论】:
标签: c# linq lambda extension-methods