我如何测试的typeof(动态)? [英] How do I test for typeof(dynamic)?

查看:144
本文介绍了我如何测试的typeof(动态)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的方法 TResult富< TSource,TResult>(IEnumerable的< TSource>源),如果 TResult 被声明为动态我要执行比其他类型的声明不同的code路径。

有关普通类型,您可以做的东西,如:

 如果(typeof运算(TResult)== typeof运算(INT))
    返回前pressionFactory.CreateExpandoFunction< TSource,TResult>();
 

如果(typeof运算(TResult)== typeof运算(动态))不能编译。

反正是有作出这种判断在运行时调用该方法的声明:

  dyanmic X =富< INT,动态>(名单);
 

由于动态本身不是一个类型是什么,我应该测试呢? IDynamicMetaObjectProvider

修改 这是一个SQL文本System.Linq.Ex pression评估的一部分。具体愿望,分支,如果 TResult 是动态的,是一些伪逻辑看起来是这样的:

 如果(类型为结构)
   选择创建初始化每个元素的结果值
否则,如果(类型为类)
   创建选择器初始化每个元素,以新的实例,并设置成员属性
否则,如果(类型是动态的)
   选择创建初始化每个元素新的`ExpandoObject`和填充/套成员属性
 

解决方案

简单地说,你不能因为没有类型的动态。在动态类型写出的对象,如果类型出现在元数据附加一个特殊的属性(动态)。从本质上说typeof运算(动态)比的typeof(对象)无异于大多数的目的。

I've got a generic method TResult Foo<TSource, TResult>(IEnumerable<TSource> source) and if TResult is declared as dynamic I want to execute a different code path than for other type declarations.

For regular types you can do stuff like:

if (typeof(TResult) == typeof(int))
    return ExpressionFactory.CreateExpandoFunction<TSource, TResult>();

But if (typeof(TResult) == typeof(dynamic)) does not compile.

Is there anyway to make this sort of determination at runtime when the method is called with the declaration:

dyanmic x = Foo<int, dynamic>(list);

Since dynamic itself isn't a type what should I be testing for? IDynamicMetaObjectProvider?

EDIT This is part of a SQL text to System.Linq.Expression evaluator. The specific desire to branch if TResult is dynamic is for some pseudo logic that looks something like this:

if (type is struct)
   create selector that initializes each element to result values
else if (type is class)
   create selector that initialize each element to new instance and set member properties
else if (type is dynamic)
   create selector that initializes each element to new `ExpandoObject` and populates/sets member properties

解决方案

Simply speaking you cannot because there is no type dynamic. In type dynamic is written out as object with a special attribute attached (Dynamic) if the type appears in metadata. Essentially saying typeof(dynamic) is no different than typeof(object) for most purposes.

这篇关于我如何测试的typeof(动态)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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