如何将动态用作通用?

Tra*_*s J 10 c# generics dynamic

如何将动态用作通用?

这个

var x = something not strongly typed;
callFunction<x>();
Run Code Online (Sandbox Code Playgroud)

还有这个

dynamic x = something not strongly typed;
callFunction<x>();
Run Code Online (Sandbox Code Playgroud)

都产生这个错误

Error   1   The type or namespace name 'x' 
could not be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能x使其足够合法用于<x>

Jon*_*eet 18

您可以使用类型推断来调用蹦床:

dynamic x = something not strongly typed;
CallFunctionWithInference(x);

...

static void CallFunctionWithInference<T>(T ignored)
{
    CallFunction<T>();
}

static void CallFunction<T>()
{
    // This is the method we really wanted to call
}
Run Code Online (Sandbox Code Playgroud)

这将根据值的执行时类型确定执行时的类型参数x,使用与将x其作为编译时类型时使用的相同类型的推断.该参数用于进行类型推断工作.

请注意,与Darin不同,我认为这一种有用的技术 - 在完全相同的情况下,您需要使用反射调用泛型方法.你可以让这一个代码动态的一部分,但保留其余的代码(从上向下通用型)的类型安全.它允许一个步骤是动态的-仅仅是单个位,你不知道类型.

  • @TravisJ:那是因为`CallFunction`本身有约束吗?你没有在问题中告诉我们:)没有`CallFunction`的约束,它应该没问题. (3认同)

svi*_*ick 5

很难说你到底想做什么。但是,如果您想调用具有与某个对象相同的类型参数的泛型方法,则不能直接执行此操作。但是您可以编写另一个方法,将您的对象作为参数,让推断dynamic类型,然后调用您想要的方法:

\n\n
void HelperMethod<T>(T obj)\n{\n    CallFunction<T>();\n}\n\n\xe2\x80\xa6\n\ndynamic x = \xe2\x80\xa6;\nHelperMethod(x);\n
Run Code Online (Sandbox Code Playgroud)\n