我正在处理表达式,我需要一个方法来接收某种类型(目前未知)的对象.像这样:
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) { }我需要的是让这个方法返回一个 Nullable 版本的 Meh,但是类型 T 来自 Meh.GetType().所以返回结果是 Nullable,其中 MehType 是 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.
有什么想法或建议吗?
谢谢
更新:我需要这个的原因是因为这个例外:
Update: the reason why I needed this is because of this exception:
未为类型System.Nullable`1[System.Int32]"和System.Int32"定义二元运算符 Equal.
return Expression.Equal(leftExpr, rightExpr);其中 leftExpr 是一个 System.Nullable1[[System.Int32 并且 rightExpr 是一个 System.Int32.
where leftExpr is a System.Nullable1[[System.Int32 and rightExpr is a System.Int32.
推荐答案如果你在编译时不知道类型,只能用 object 来表达 - 并且尽快你装箱一个可为空的值类型,你最终得到一个空引用,或者一个装箱的不可空值类型.
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.
更多推荐
如何创建 Nullable<T>从类型变量?
发布评论