C# SQL Server의 iSnull () 함수와 동등합니다.
-
05-07-2019 - |
문제
SQL Server에서는 사용할 수 있습니다 IsNull()
함수 값이 null인지 확인하고 다른 값을 반환하십시오. 이제 C#에 비슷한 것이 있는지 궁금합니다.
예를 들어, 나는 다음과 같은 일을하고 싶습니다.
myNewValue = IsNull(myValue, new MyValue());
대신에:
if (myValue == null)
myValue = new MyValue();
myNewValue = myValue;
감사.
해결책
Null Coalescing이라고합니다.??
) 운영자:
myNewValue = myValue ?? new MyValue();
다른 팁
안타깝게도 DBNULL과 함께 작동하는 NULL Coalescing 연산자와 동등한 것은 없습니다. 이를 위해서는 3 대 연산자를 사용해야합니다.
newValue = (oldValue is DBNull) ? null : oldValue;
Equals 메소드 사용 :
object value2 = null;
Console.WriteLine(object.Equals(value2,null));
public static T isNull<T>(this T v1, T defaultValue)
{
return v1 == null ? defaultValue : v1;
}
myValue.isNull(new MyValue())
DB Nulls와 함께 작업하기 위해 VB 응용 프로그램을위한 무리를 만들었습니다. VB의 내장 CXXX 기능과 유사하기 때문에 CXXX2라고합니다.
내 CLR 확장 프로젝트에서 볼 수 있습니다
http://www.codeplex.com/clrextensions/sourcecontrol/fileview.aspx?itemid=363867&changesetid=17967
두 가지 기능을 작성합니다
//When Expression is Number
public static double? isNull(double? Expression, double? Value)
{
if (Expression ==null)
{
return Value;
}
else
{
return Expression;
}
}
//When Expression is string (Can not send Null value in string Expression
public static string isEmpty(string Expression, string Value)
{
if (Expression == "")
{
return Value;
}
else
{
return Expression;
}
}
그들은 아주 잘 작동합니다
Datarow 유형에서 다음 확장 방법을 사용하고 있습니다.
public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
{
string val = defaultValue;
if (row.Table.Columns.Contains(colName))
{
if (row[colName] != DBNull.Value)
{
val = row[colName]?.ToString();
}
}
return val;
}
용법:
MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");
쿼리 결과가 해당 열에 대해 널 값이 아닌 값이 없으면 데이터 가능한 객체가 해당 열을 제공하지 않기 때문에 열의 존재를 먼저 확인하고 있습니다.
아래 방법을 사용하십시오.
/// <summary>
/// Returns replacement value if expression is null
/// </summary>
/// <param name="expression"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static long? IsNull(long? expression, long? replacement)
{
if (expression.HasValue)
return expression;
else
return replacement;
}
/// <summary>
/// Returns replacement value if expression is null
/// </summary>
/// <param name="expression"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string IsNull(string expression, string replacement)
{
if (string.IsNullOrWhiteSpace(expression))
return replacement;
else
return expression;
}
질문이 좀 어리석기 때문에 이것은 농담의 절반을 의미합니다.
public static bool IsNull (this System.Object o)
{
return (o == null);
}
이것은 확장 방법이지만 System.Object를 확장하므로 현재 사용하는 모든 객체에는 isnull () 메소드가 있습니다.
그런 다음 다음을 수행하여 수많은 코드를 저장할 수 있습니다.
if (foo.IsNull())
슈퍼 절름발이 대신 :
if (foo == null)