我已经根据答案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);
}
编辑-更新以包括对它在基类以及继承它的类中起作用的要求。
最佳答案
更改扩展方法的签名,如下所示:(删除初始的“ AcObject”)
public static Dictionary<string, string> GetValidationList<TProperty>(
this AcObject source, Expression<Func<AcObject, TProperty>> propertyLambda)
最后一段代码中也有一个拼写错误:
AcObject myObject = new AcObject();
myObject.GetValidationList(a => a.Type); // call the extension method on the instance
包含的那些类型参数(AcObject和TProperty)是占位符,代表您在调用方法时指定的实际类型。通过在方法中命名第一个“ AcObject”,您将隐藏也称为“ AcObject”的实际类(因此
this AcObject source
中的“ AcObject”不再引用您的类)。鉴于您的问题已更新,请像这样修改您的签名。您基本上在一开始就正确了,只需将类型参数的名称从“ AcObject”更改为不是您的类名称的其他名称,例如“ T”:
public static Dictionary<string, string> GetValidationList<T, TProperty>(
this T source, Expression<Func<T, TProperty>> propertyLambda)
然后可以使用不同的类来调用它:
AcObject myObject = new AcObject();
myObject.GetValidationList(a => a.Id);
OtherObject myOtherObject = new OtherObject();
myOtherObject.GetValidationList(a => a.AssetTag);
关于c# - 无法使用Lambda的扩展方法访问实例变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26009078/