How do I test for typeof(dynamic)?

送分小仙女□ 提交于 2019-12-22 04:21:06

问题


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

回答1:


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.




回答2:


It is not necessary for object declared as dynamic to be some specific type of object. It can be a subclass of DynamicObject (and thus provide specific logic for operations lookup), but it can be a normal object as well (as @JaredPar said).

Maybe, if you explain what sort of branch you want to make for dynamic objects it would be possible to find better solution.



来源:https://stackoverflow.com/questions/1598731/how-do-i-test-for-typeofdynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!