无法与扩展方法来访问实例变量和λ
问题描述:
我已经创建了一个扩展方法为每一个答案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);
答
public static class stat
{
public static void GetValidationList( this AcObject source)
{
Console.WriteLine(source.Id);
}
}
public class AcObject
{
public int Id { get; set; }
}
用法:
AcObject myObject = new AcObject();
myObject.GetValidationList();
+0
感谢您的及时答复,但我正在寻找包含lamda表达式的内容。 – 2014-09-24 05:33:29
这将是巨大的前很简单,为什么OP需要更改签名。看起来他误解了类型参数的概念。 – Dennis 2014-09-24 05:28:41
正如@丹尼斯提到的,我认为我在这里误解了一些东西。如果我如上所述进行上述更改,那么对于显式为'AcObject'的任何对象都适用,但对于继承'AcObject'的某些对象失败。我会修改我的OP来包含一个例子。 – 2014-09-24 05:33:00
要明确,通过“失败”,我的意思是它只在我的lamda expresion中列出了'AcObject'的属性,而不是当前类型的属性。 '公共类AcAsset:AcObject {...}'然后'AcAsset asset = new AcAsset()。GetValidationList(a => a。'在这里它只列出'AcObject'的成员 – 2014-09-24 05:38:53