我根据答案 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);
