How to create a Nullable<T> from a Type variable?

江枫思渺然 提交于 2019-12-10 17:54:18

问题


I'm working with expressions and I need a method which receives an object of some type (currently unknown). Something like this:

public static void Foobar(object Meh) { }

What I need to is make this method return a Nullable<T> version of Meh, but the type T is from Meh.GetType(). So the return would be Nullable<MehType>, where MehType is the type of Meh.

Any ideas or suggestions?

Thanks

Update: the reason why I needed this is because of this exception:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.

return Expression.Equal(leftExpr, rightExpr);

where leftExpr is a System.Nullable1[[System.Int32 and rightExpr is a System.Int32.


回答1:


If you don't know the type at compile time, the only way of expressing it is as object - and as soon as you box a nullable value type, you end up with either a null reference, or a boxed non-nullable value type.

So these snippets are exactly equivalent in terms of the results:

int? nullable = 3;
object result = nullable;

int nonNullable = 3;
object result = nonNullable;

In other words, I don't think you can really express what you're trying to do.




回答2:


Do you have to use Meh.GetType() instead of a generic? What about this?

public static Nullable<T> Foobar<T>(T Meh) where T : struct { }

I'm making the assumption that "some type" does not mean "any type", because the solution above would only work with value types.



来源:https://stackoverflow.com/questions/7070791/how-to-create-a-nullablet-from-a-type-variable

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