簡體   English   中英

確定C#中對象的值

[英]Determine value of object in C#

確定對象在C#中等於數字零(0)還是string.empty的最佳方法是什么?

編輯:對象可以等於任何內置的System.Value類型或引用類型。

源代碼:

public void MyMethod(object input1, object input2)
{
    bool result = false;
    object compare = new object();

    if(input != null && input2 != null)
    {
        if(input1 is IComparable && input2 is IComparable)
        {
            //do check for zero or string.empty
            //if input1 equals to zero or string.empty
            result = object.Equals(input2);

            //if input1 not equals to zero or string.empty
            result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
        }
    }
}

這怎么了

public static bool IsZeroOrEmptyString(object obj)
{
    if (obj == null)
        return false;
    else if (obj.Equals(0) || obj.Equals(""))
        return true;
    else
        return false;
}

使用經過輕微修改的Jonathan Holland代碼示例,以下是可行的解決方案:

static bool IsZeroOrEmpty(object o1)
{
    bool Passed = false;
    object ZeroValue = 0;

    if(o1 != null)
    {
        if(o1.GetType().IsValueType)
        {
            Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
        }
        else
        {
            if (o1.GetType() == typeof(String))
            {
                Passed = o1.Equals(String.Empty);
            }
        }
    }

    return Passed;
}

邁克爾,您需要在此處提供更多信息。

可以將字符串與null或string.Empty進行比較,方法是:

string x = "Some String"
if( string.IsNullOrEmpty(string input) ) { ... }

可以使用簡單的==測試將int,小數,雙精度(和其他數值類型)與0(零)進行比較

int x = 0;
if(x == 0) { ... }

您還可以使用?來具有可為空的值類型。 實例化它們時的操作符。 這使您可以將值類型設置為null。

int? x = null;
if( !x.HasValue ) {  }

對於任何其他對象,簡單的== null測試將告訴您它是否為null

object o = new object();
if( o != null ) { ... }   

希望能為我們提供一些啟示。

不太清楚其背后的原因,因為.Equals是引用類型上的引用相等,而值類型上是值相等。

這似乎可行,但是我懷疑您想要什么:

    static bool IsZeroOrEmpty(object o1)
    {
        if (o1 == null)
            return false;
        if (o1.GetType().IsValueType)
        {                
            return (o1 as System.ValueType).Equals(0);
        }
        else
        {
            if (o1.GetType() == typeof(String))
            {
                return o1.Equals(String.Empty);
            }

            return o1.Equals(0);
        }
    }

如果您在談論字符串,是指null還是string.empty?

如果(String.IsNullOrEmpty(obj作為字符串)){...做某事}

  • 愛信

在第一種情況下,通過測試它是否為null。 在第二種情況下,通過測試它是否為string.empty(您回答了自己的問題)。

我應該補充一點,一個對象永遠不能等於0。盡管一個對象變量可以有一個空引用(實際上這意味着該變量的值為0;盡管在這種情況下沒有對象)

obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM