[問題] 繼承屬性疑問

作者: justlike5566 (5566天下無敵)   2018-03-15 22:08:33
先附上code
class TestA
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class TestB : TestA
{
public string CName { get; set; }
}
class Program
{
static void Main(string[] args)
{
TestA ta = getTestA();
TestB tb = getTestA() as TestB;
var temp = tb;
}
private static TestA getTestA()
{
return new TestA()
{
ID = 1,
Name = "AA",
Age = 18
};
}
}
目的是讓TestB繼承的屬性直接給值而不用在B那邊一個一個寫入
爬了一天文沒找到相關的資訊及解法
求有沒有相類似的關鍵字讓小弟可以去查
作者: t64141 (榕樹)   2018-03-15 22:28:00
TestB包含一個屬性TestA, newTestB(){ testA = getTestA();}
作者: pzyc79   2018-03-15 22:28:00
看不懂你問題是什麼
作者: t64141 (榕樹)   2018-03-15 22:29:00
不過還是要看你這兩個物件在邏輯上究竟是否適合用包含取代繼承
作者: pzyc79   2018-03-15 22:33:00
把return new TestA()改成return new TestB()可能是你要的
作者: Litfal (Litfal)   2018-03-16 08:04:00
你反了,父類不能直接轉子類阿,動物又不一定是狗
作者: s4300026 (s4300026)   2018-03-16 08:37:00
所以應該寫個給值方法,new B,給父類別值請參考 #1QgW7iUS (C_and_CPP)程式碼第222行,你可以new子類別完後,return前寫你想return的父類別值
作者: snowlike (.zZ)   2018-03-16 10:40:00
泛型 static T Get<T>() where T : TestA, new() { ..
作者: landlord (91)   2018-03-17 00:00:00
AutoMapper

Links booklink

Contact Us: admin [ a t ] ucptt.com