如何可以动态用作一个通用的? [英] How can a dynamic be used as a generic?

查看:108
本文介绍了如何可以动态用作一个通用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用动态作为通用?

How can I use a dynamic as a generic?

var x = something not strongly typed;
callFunction<x>();



and this

dynamic x = something not strongly typed;
callFunction<x>();



都产生这个错误

both produce this error

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

我能做些什么,以 X ,使其足够正当的< X>

What can I do to x to make it legitimate enough to be used in <x>?

推荐答案

您可以使用类型推理来排序蹦床的呼唤?

You could use type inference to sort of trampoline the call:

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
}

这将决定基于价值的执行时类型在执行时的类型参数 X ,使用同一种类型推断它会如用x 有,作为其的编译时间的类型。该参数的只有的存在,使类型推断的工作。

This will determine the type argument at execution time based on the execution-time type of the value of x, using the same kind of type inference it would use if x had that as its compile-time type. The parameter is only present to make type inference work.

请注意,不像达林,我相信这个的的一有用的技术 - ,正是在预动态你最终调用带有反射泛型方法相同的情况。你可以让这个的有一个的代码动态的一部分,但保留的休息码(从向下通用型)的类型安全的。它允许的有一个的步骤是动态的 - 只是单个位,你不知道类型

Note that unlike Darin, I believe this is a useful technique - in exactly the same situations where pre-dynamic you'd end up calling the generic method with reflection. You can make this one part of the code dynamic, but keep the rest of the code (from the generic type on downwards) type-safe. It allows one step to be dynamic - just the single bit where you don't know the type.

这篇关于如何可以动态用作一个通用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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