作者justlike5566 (5566天下无敌)
看板C_Sharp
标题[问题] 继承属性疑问
时间Thu Mar 15 22:08:33 2018
先附上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那边一个一个写入
爬了一天文没找到相关的资讯及解法
求有没有相类似的关键字让小弟可以去查
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.40.18.78
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1521122915.A.818.html
1F:→ t64141: TestB包含一个属性TestA, newTestB(){ testA = getTestA() 03/15 22:28
2F:→ t64141: ;} 03/15 22:28
3F:→ pzyc79: 看不懂你问题是什麽 03/15 22:28
4F:→ t64141: 不过还是要看你这两个物件在逻辑上究竟是否适合用包含取代 03/15 22:29
5F:→ t64141: 继承 03/15 22:29
6F:→ pzyc79: 把return new TestA()改成return new TestB()可能是你要的 03/15 22:33
7F:→ Litfal: 你反了,父类不能直接转子类阿,动物又不一定是狗 03/16 08:04
8F:推 s4300026: 所以应该写个给值方法,new B,给父类别值 03/16 08:37
10F:推 s4300026: 程式码第222行,你可以new子类别完後,return前写你想re 03/16 08:42
11F:→ s4300026: turn的父类别值 03/16 08:42
12F:推 snowlike: 泛型 static T Get<T>() where T : TestA, new() { .. 03/16 10:40
13F:→ landlord: AutoMapper 03/17 00:00