How can I pass in a func with a generic type parameter?

后端 未结 4 1763
死守一世寂寞
死守一世寂寞 2020-12-01 17:59

I like to send a generic type converter function to a method but I can\'t figure out how to do it.

Here\'s invalid syntax that explains what I like to achieve, the p

相关标签:
4条回答
  • 2020-12-01 18:14

    You cannot have instances of generic functions or actions - all type parameters are defined upfront and cannot be redefined by the caller.

    An easy way would be to avoid polymorphism altogether by relying on down-casting:

    public void SomeUtility(Func<Type, object, object> converter)
    {
        var myType = (MyType)converter(typeof(MyType), "foo");
    }
    

    If you want type safety, you need to defer the definition of the type parameters to the caller. You can do this by composing a generic method within an interface:

    public void SomeUtility(IConverter converter)
    {
        var myType = converter.Convert<MyType>("foo");
    }
    
    interface IConverter
    {
       T Convert<T>(object obj);
    }
    

    Edit:

    If the 'converter type' is known at the call-site, and only this type will be used inside the utility method, then you can define a generic type on the method and use that, just like other posters have suggested.

    0 讨论(0)
  • 2020-12-01 18:15

    You have to know the T type at compile-time to use it. The T can either be specified at class-level or at method-level.

    class SomeClass<T> {
        public void SomeUtility(Func<object, T> converter) {
            var myType = converter("foo"); // Already is the T-type that you specified.
        }
    }
    

    or

    public void SomeUtility<T>(Func<object, T> converter) {
        var myType = converter("foo"); // Already is the T-type that you specified.
    }
    
    0 讨论(0)
  • 2020-12-01 18:26

    You need to make SomeUtility generic as well. Doing this and fixing the syntax gives:

    public void SomeUtility<T>(Func<object,T> converter)
    {
        var myType = converter("foo");
    }
    
    0 讨论(0)
  • 2020-12-01 18:28
    public void SomeUtility<T>(Func<object, T> converter)
    {
        var myType = converter("foo");
    }
    

    and then:

    SomeUtility(arg => new MyType());
    

    The generic type inference will work in this case.

    0 讨论(0)
提交回复
热议问题