具有相同值的结构是否相同?

时间:2012-08-29 14:21:08

标签: c# data-structures

考虑这个结构。

public struct myStruct{
    public int value1;
    public int value2;
    public int value3;

    public myStruct(int val1, int val2, int val3){
        value1 = val1;
        value2 = val2;
        value3 = val3;
    }
}

现在考虑我有一些myStruct类型的列表:

public List<myStruct> myList = new List<myStruct>();

现在我使用相同的值实例化myStruct的两个不同版本:

myStruct s1 = new myStruct(1,2,3);
myStruct s2 = new myStruct(1,2,3);

然后我将第一个实例添加到myList

myList.Add(s1);

然后我做一个简单的检查,看看第二个实例是否在列表中:

bool structsEqual = myList.Contains(s2);

structsEqual是真还是假?

4 个答案:

答案 0 :(得分:1)

您拥有所有代码,您可以将其放入程序中并运行它,看看会发生什么。我使用LinqPad,这就是我得到的......

public List<myStruct> myList = new List<myStruct>(); 

void Main()
{
    myStruct s1 = new myStruct(1,2,3); 
    myStruct s2 = new myStruct(1,2,3); 

    myList.Add(s1); 

    bool structsEqual = myList.Contains(s2); 

    structsEqual.Dump();
}

public struct myStruct{ 
    public int value1; 
    public int value2; 
    public int value3; 

    public myStruct(int val1, int val2, int val3){ 
        value1 = val1; 
        value2 = val2; 
        value3 = val3; 
    } 
} 

结果=“真实”

答案 1 :(得分:1)

Structsvalue types,因此答案为True

答案 2 :(得分:1)

有趣的是,这个特定代码将等于true,但如果struct包含对象而没有系统类型,那么你必须为此实现IComparable并不总是返回false。

public struct myStruct
{ 
    public MyOwnType value1; 
    public int value2; 
    public int value3; 

    public myStruct(MyOwnType val1, int val2, int val3){ 
        value1 = val1; 
        value2 = val2; 
        value3 = val3; 
    } 
}

public class MyOwnType
{
    public int Id { get; set; }

    public MyOwnType(int id)
    {
        this.Id = id;
    }
}

要使Contains工作,您需要实现IComparable:

public class MyOwnType : IComparable
{
    public int Id { get; set; }

    public MyOwnType(int id)
    {
        this.Id = id;
    }

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;

        MyOwnType other = obj as MyOwnType;
        if (other != null)
            return this.Id.CompareTo(other.Id);
        else
            throw new ArgumentException("Object is not a MyOwnType");
    }
}

答案 3 :(得分:0)

快速谷歌导致以下链接:

http://www.java2s.com/Tutorial/CSharp/0120__struct/Valuetypeequalitydefaultbehavior.htm

所以是的,它将是真的