【发布时间】:2017-09-29 13:17:57
【问题描述】:
我想从不同的 BindingSources 创建一些 Material 类的对象。
如何编写 lambda 表达式以便不必在构造函数中指定类型?
例子:
namespace test1
{
class Program
{
static void Main(string[] args)
{
// Wood class defined in other assembly
List<Wood> woodList = new List<Wood>();
woodList.Add(new Wood("Oak", 750));
woodList.Add(new Wood("Spruce", 450));
BindingSource bs = new BindingSource();
bs.DataSource = woodList;
//don't want to specify type in code
Material<Wood> z2 = new Material<Wood>(1, bs, (i) => (Wood)(bs.Current));
// Can I create object this way with lambda expression ?
//Material<t> z1 = new Material<t>(1, bs, (lambda expression ??));
}
}
public class Material<T> where T : class
{
public int ID { get; set; }
private T _item;
public Material(
int _id,
BindingSource _bindSource,
Func<object, T> _getTypeParameter)
{
this.ID = _id;
T _item = _getTypeParameter(_bindSource.Current);
}
}
}
【问题讨论】:
标签: c# generics lambda expression