iT邦幫忙

0

介面實作 MemberwiseClone()疑問

各位大大
小弟最近接觸C#
實作一個ICloneable介面時,使用MemberwiseClone();
不知道該怎麼解決,代碼如下

在this.MemberwiseClone()這邊會出現紅字
CS0266 無法將類型 'object' 隱含轉換成 'Test_0029_ICloneable_IConparable.My_Item'。已存在明確轉換 (是否漏了轉型?)

.NET是netcoreapp3.1

using System;

namespace Test_0029_ICloneable_IConparable_IFormattable
{
    public class My_Item : ICloneable, IComparable
    {
        int _Key_Num;
        string _Name;

        public My_Item(int Key_NUM, string Name)
        {
            _Key_Num = Key_NUM;
            _Name = Name;
        }

        public object Clone()  //實作一個clone
        {
            My_Item my_Item =  this.MemberwiseClone();
            my_Item._Name += "._Copy"; 
            return my_Item;
        }

        public int CompareTo(object obj)  //實作一個clone
        {
            My_Item my_Item = obj as My_Item;       //嘗試複製為My_Item物件
            if (my_Item == null) { return -1; }  //如果無法複製則回傳False
            return (this._Key_Num == my_Item._Key_Num) ? this._Key_Num : 0;  //如果_Key_Num相同,則回傳Ture否則為False
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            My_Item my_Item = new My_Item(1, "my_Item");
            var my_Item_copy = my_Item.Clone();
            Console.WriteLine(my_Item.CompareTo(my_Item_copy));
        }
    }
}

看更多先前的討論...收起先前的討論...
lazywayne iT邦新手 5 級 ‧ 2020-05-05 16:06:22 檢舉
所有Class其實都繼承Object類別沒錯吧?
這樣子this雖然屬於My_Item物件但是也能用MemberwiseClone嗎?
https://dotnetfiddle.net/0PcpIA 幫你放上去跑...所以你的問題是?
lazywayne iT邦新手 5 級 ‧ 2020-05-06 09:27:22 檢舉
MemberwiseClone那邊會是紅字

CS0266 無法將類型 'object' 隱含轉換成 'Test_0029_ICloneable_IConparable.My_Item'。已存在明確轉換 (是否漏了轉型?)
lazywayne iT邦新手 5 級 ‧ 2020-05-06 09:37:43 檢舉
睡一覺後腦袋清醒,代碼改好了

using System;

namespace Test_0029_ICloneable_IConparable
{
public class My_Item : ICloneable, IComparable
{
public int _Key_Num;
public string _Name;

public My_Item(int Key_NUM, string Name)
{
_Key_Num = Key_NUM;
_Name = Name;
}

public object Clone() //實作一個clone
{
var my_Item = this.MemberwiseClone() as My_Item;
my_Item._Name += "._Copy";
return my_Item;
}

public int CompareTo(object obj) //實作一個clone
{
My_Item my_Item = obj as My_Item; //嘗試複製為My_Item物件
if (my_Item == null) { return -1; } //如果無法複製則回傳False
return (this._Key_Num == my_Item._Key_Num) ? this._Key_Num : 0; //如果_Key_Num相同,則回傳Ture否則為False
}
}

class Program
{
static void Main(string[] args)
{
My_Item my_Item = new My_Item(1, "my_Item");
var my_Item_copy = my_Item.Clone() as My_Item;

Console.WriteLine("my_Item.CompareTo(my_Item_copy) = {0}", my_Item.CompareTo(my_Item_copy));

Console.WriteLine("my_Item._Key_Num = {0}", my_Item._Key_Num);
Console.WriteLine("my_Item._Name = {0}", my_Item._Name);

Console.WriteLine("my_Item_copy._Key_Num = {0}", my_Item_copy._Key_Num);
Console.WriteLine("my_Item_copy._Name = {0}", my_Item_copy._Name);
}
}
}
:D

尚未有邦友回答

立即登入回答