各位大大
小弟最近接觸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));
}
}
}