我怎么能传递一个FUNC一个泛型类型参数? [英] How can I pass in a func with a generic type parameter?

查看:570
本文介绍了我怎么能传递一个FUNC一个泛型类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送一个泛型类型转换器功能的一种方法,但我无法弄清楚如何做到这一点。

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

下面是无效的语法,说明我喜欢来实现的,问题是我不知道怎么跟我一起FUNC指定泛型类型:

Here's invalid syntax that explains what I like to achieve, the problem is I don't know how to specify the generic type together with my func:

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



编辑(另见我与劳伦斯的意见讨论):通过通用类型转换器我的意思,我想在这可以转换成任何类型的强℃的转换器来传递; T> (不是对象),所以在我的方法的下一行可能是:

Edit (see also my discussion in the comments with Lawrence) : By "generic type converter" I meant I would like to pass in a converter that can convert to any strong type <T> (not object), so the next line in my method could be:

var myOtherType = converter<MyOtherType>("foo");



我想作为参数传递会是这个样子的委托:

The delegate I like to pass as a parameter would look something like this:

private delegate TOutput myConverterDelegate<TOutput>(object objectToConvert);

这更多的是一种语法/ C#的探索,现在,把事情做好,我可能会使用一个接口,而不是,但我希望这是可能的一个FUNC /委托完成的。

This is more a syntax / C# exploration now, to get things done I will probably use an interface instead, but I do hope this is possible to accomplish with a func/delegate.

推荐答案

您不能有泛型函数或操作实例 - 所有类型参数被定义前期和不能由呼叫者重新定义

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);
}



编辑:

如果该变换类型在调用站点是已知的,也只有这个类型将实用方法中使用,那么你可以在方法定义泛型类型和使用,就像其他海报建议。

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.

这篇关于我怎么能传递一个FUNC一个泛型类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆