C# 将int转换为可为空的int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18020146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:04:13  来源:igfitidea点击:

convert int to nullable int?

c#asp.net

提问by user2582770

I need to know how to convert an int to a nullable int. However, I keep getting an error "The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'." Any solution. It needs to be Microsoft SQL Server's nullable int type.

我需要知道如何将 int 转换为可为 null 的 int。但是,我不断收到错误消息“未为类型“System.Nullable`1[System.Int32]”和“System.Int32”定义二元运算符 Equal。” 任何解决方案。它需要是 Microsoft SQL Server 的可为空的 int 类型。

 somevalue = Expression.Constant(something.GetValue(some,null).To<Nullable<System.Int32>> ());

public static T To<T>(this object obj)
    {
        Type t = typeof(T);
        Type u = Nullable.GetUnderlyingType(t);

        if (u != null)
        {
            if (obj == null)
                return default(T);

            return (T)Convert.ChangeType(obj, u);
        }
        else
        {
            return (T)Convert.ChangeType(obj, t);
        }
    }'

采纳答案by Eric Lippert

That Tocode seems to be you trying to construct a Constantof nullable type when given a value of non-nullable type but that is not at all the right way to go about this. The way you're trying to do this indicates that you have a misunderstanding about how boxed value types work.

To代码似乎是您Constant在给定不可空类型的值时试图构造可空类型,但这根本不是解决此问题的正确方法。您尝试执行此操作的方式表明您对装箱值类型的工作方式存在误解。

That error message indicates that you are constructing a binary operator expression tree node which has as its operands an expression node of nullable int type and an expression node of int type. That's not legal; they have to be bothnullable int. What you should be doing is wrapping the non-nullable int expression tree node in a Convertexpression tree nodewhich converts it to a nullable int, and then pass thatto the binary operator expression tree node constructor.

该错误消息表明您正在构建一个二元运算符表达式树节点,该节点的操作数是一个可空 int 类型的表达式节点和一个 int 类型的表达式节点。这是不合法的;它们都必须是可空的 int。您应该做的是将不可为空的 int 表达式树节点包装在一个Convert表达式树节点中,该节点将其转换为可空的 int,然后将传递给二元运算符表达式树节点构造函数。

That is, this is wrong:

也就是说,这是错误的:

var someIntExpr = Expression.Constant(123, typeof(int));
var someNubIntExpr = Expression.Constant(null, typeof(int?));
var badEq = Expression.Equal(someIntExpr, someNubIntExpr);

This is right:

这是对的:

var goodEq = Expression.Equal(Expression.Convert(someIntExpr, typeof(int?)),  someNubIntExpr);

So why is what you're doing wrong?

那你为什么做错了?

You have a method To<T>which returns a T. It correctly takes in an intand returns the equivalent int?. So then what? You pass that to Expression.Constant, which boxes the nullable int into a boxed int, and then makes a constant out of that. You believe that there is such a thing as a boxed nullable value type, but there is not! A nullable value type boxes either to a null reference or to a boxed non-nullable value type.

您有一个To<T>返回T. 它正确地接受 anint并返回等效的int?。那么呢?您将其传递给Expression.Constant,它将可以为空的 int装箱为装箱的 int,然后从中生成一个常量。您相信有装箱的可为空值类型这样的东西,但实际上并没有!可为空值类型装箱到空引用或装箱的不可为空值类型。

So you could also solve your problem by not doing any of this crazy stuff in the first place. If you have a boxed int in hand, and you need a constant expression tree node of nullable type, just provide the type.

所以你也可以通过不做任何这些疯狂的事情来解决你的问题。如果您手头有一个装箱的 int,并且您需要一个可为空类型的常量表达式树节点,只需提供 type

Expression.Constant(someBoxedIntValue, typeof(int?))

Done. So: wrapping up, you have two solutions:

完毕。所以:总结一下,你有两个解决方案:

  • If you have a boxed int in hand, pass it and the nullable value type you want to the Constantfactory, or
  • if you have an expression node of type int in hand then use the Convertexpression node factory, and pass it and the desired type to that.
  • 如果您手头有一个装箱的 int,请将它和您想要的可为空的值类型传递给Constant工厂,或者
  • 如果你手头有一个 int 类型的表达式节点,那么使用Convert表达式节点工厂,并将它和所需的类型传递给它。

Both will give you back an expression node of the correct type to be compared to another nullable int.

两者都会为您返回一个正确类型的表达式节点,以便与另一个可为空的 int 进行比较。

回答by dotixx

int i = 1;
int? k;
k = i as int?;

Like this you will convert iwhich is an int to a nullable int ;)

像这样,您会将iint转换为可为空的 int ;)

int?is the short version of Nullable<int>.

int?是 的简短版本Nullable<int>

回答by traxs

int test = 0; // set int

int? num = test; // convert test to a nullable int

num = null; // set num as null

回答by Michael Gunter

Typically, you convert an intan int?using a cast.

通常情况下,一个转换intint?使用演员。

int? myNullable = (int?) 15;
int myInt = (int) myNullable;

回答by ToddB

Does something simpler like this not work?

像这样更简单的东西不起作用吗?

int i; 
int? temp = int.TryParse(<your value>, out i) ? (int?)i : null;

回答by Pangamma

Here you go. A generic string to nullable primitive solution.

干得好。可空原始解决方案的通用字符串。

int? n = "  99 ".ToNullable<int>(); 

/// <summary>
/// Developed by Taylor Love
/// </summary>
public static class ToNullableStringExtension
{
    /// <summary>
    /// <para>More convenient than using T.TryParse(string, out T). 
    /// Works with primitive types, structs, and enums.
    /// Tries to parse the string to an instance of the type specified.
    /// If the input cannot be parsed, null will be returned.
    /// </para>
    /// <para>
    /// If the value of the caller is null, null will be returned.
    /// So if you have "string s = null;" and then you try "s.ToNullable...",
    /// null will be returned. No null exception will be thrown. 
    /// </para>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="p_self"></param>
    /// <returns></returns>
    public static T? ToNullable<T>(this string p_self) where T : struct
    {
        if (!string.IsNullOrEmpty(p_self))
        {
            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
            if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
        }

        return null;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions

https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions