Sна*_*ƒаӽ 5 c# inheritance multiple-inheritance expression-trees
我有两个具有某些公共属性的类(或模型)。例如:
public class Model1
{
public int Common1 { get; set; }
public int Common2 { get; set; }
public int Prop11 { get; set; }
public int Prop12 { get; set; }
}
public class Model2
{
public int Common1 { get; set; }
public int Common2 { get; set; }
public int Prop21 { get; set; }
public int Prop22 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要编写一个可以接受成员选择器表达式的方法,其中要选择的成员可以来自两个模型之一。这就是我的意思:
public List<T> GetAnon<T>(Expression<Func<??, T>> selector) // <-- intriguing part
{
// codes to extract property names from selector and create the return object of type T
}
// And this is an example usage of the method
// At this point, I don't know which model Common1, Prop11 or Prop21 belongs to
var anonObj = GetAnon(m => new { m.Common1, m.Prop11, m.Prop21 });
// anonObj = { Common1 = VALUE_1, Prop11 = VALUE_2, Prop21 = VALUE_3 }
Run Code Online (Sandbox Code Playgroud)
请注意,selector传递的内容同时从Model1和中选择Model2。
我当前的解决方案:创建一个具有通用属性的模型,例如Model,拥有Model1并Model2继承Model各个模型中的其余属性。然后创建另一个TempModel继承模型,Model并向其中添加非公共属性。像这样:
public class Model
{
public int Common1 { get; set; }
public int Common2 { get; set; }
}
public class Model1 : Model
{
public int Prop11 { get; set; }
public int Prop12 { get; set; }
}
public class Model2
{
public int Prop21 { get; set; }
public int Prop22 { get; set; }
}
public class TempModel : Model
{
public int Prop11 { get; set; }
public int Prop12 { get; set; }
public int Prop21 { get; set; }
public int Prop22 { get; set; }
}
// Finally, first type parameter can be TempModel
public List<T> GetAnon<T>(Expression<Func<TempModel, T>> selector)
{
// codes to extract property names from selector and create the return object of type T
}
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是,如果Model1和Model2变化,这他们很容易,我会记得要进行更改TempModel为好,这是我想避免的。另外,我想避免将属性名称作为字符串传递,以免丢失智能提示。
我该如何实现?显然,在C#中不可能实现多重继承,否则我的问题就变得微不足道了。
编辑:
我已经对问题进行了编辑,以反映我的实际需求(尽管我不确定这是否真的有帮助)。我实际上需要T在方法内部创建并返回一个匿名类型的对象GetAnon()。要创建对象,我需要属性的名称,以便可以执行检索(使用SQL)。我不想通过将名称作为字符串传递而失去智慧。另外,在调用方法时,我不知道哪个属性来自哪个模型,我只知道属性名称。
我认为最简单的方法就是使用:
public List<T> GetAnon<T>(Expression<Func<Model1, Model2, T>> selector) {
}
Run Code Online (Sandbox Code Playgroud)
对于调用者来说可能有点不方便,因为他必须记住(或通过反复试验找出)哪个模型具有他需要的属性,但我认为不便很小,好处足够大(不需要额外的类) ,正如您所说,维护起来很容易出错)。
用法将是:
var propNames = GetAnon((m1, m2) => new { m1.Common1, m1.Prop11, m2.Prop21 });
Run Code Online (Sandbox Code Playgroud)