使用lambda表达式作为泛型类型参数的构造方法

时间:2017-09-29 13:17:57

标签: c# generics lambda expression

我想从不同的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);
    }
}
}

1 个答案:

答案 0 :(得分:2)

  

我可以用lambda表达式以这种方式创建对象吗?

简单地说:不,你在调用构造函数时提供泛型参数。但是,您可以将构造函数调用包装到通用工厂方法中:

Material<T> CreateMaterial<T>(int _id, BindingSource _bindSource, Func<object, T> _getTypeParameter)
{
    return new Material<T>(_id, _bindingSource, _getTypeParamer);
}

现在编译器能够从传递的参数中自动推断出类型:

 Material<Wood> z2 = CreateMaterial(1, bs, (i) => (Wood)(bs.Current));