我有一個BL類,名爲:A,DTO類,名爲:DTO。現在假設我想在我的DTO中添加更多的屬性。所以,我從我現有的DTO派生出新的DTO類,並添加屬性it.Below是代碼:C#多態性問題
namespace TestConsole
{
class test
{
static void Main(string[] args)
{
B b = new B();
b.D.ID = 1;
b.D.Name = "4";
MyBLMethod(b);
}
static void MyBLMethod(A b)
{
MyDALMethod(b.D);
}
static void MyDALMethod(DTO dto)
{
int i = dto.ID;
string name = ((MyDTO)dto).Name;//I could not do this
//because i will get object cast error as i can't cast from
//parent to child
}
}
public class DTO
{
public int ID = 99;
public DTO()
{
}
public DTO(DTO source)
{
ID = source.ID;
}
}
public class MyDTO : DTO
{
public string Name = "";
public MyDTO() { }
public MyDTO(MyDTO source)
: base(source)
{
Name = source.Name;
}
}
public class A
{
private DTO _d;
public A()
{
D = new DTO();
}
public DTO D
{
get { return _d; }
set { _d = value; }
}
}
public class B : A
{
private MyDTO _md;
public B()
{
_md = new MyDTO();
}
public MyDTO D
{
get { return _md; }
set { _md = value; }
}
}
}
從主(你可以把它作爲UI)我打電話MyBLMethod(存在於BL庫)和將類對象傳遞給它,並從BL存儲庫中調用我的DAL。在DAL我寫了這樣的:
static void MyDALMethod(DTO dto)
{
int i = dto.ID;
string name = ((MyDTO)dto).Name;//I could not do this
//because i will get object cast error as i can't cast from
//parent to child
}
你能否建議我如何得到我的DAL中新擴展的屬性(在這個例子中的名稱)。
你確定cast會拋出異常嗎? – strager 2009-11-06 22:20:46
是的,上面的投射會拋出「無法投射'TestConsole.DTO'類型的對象來鍵入'TestConsole.MyDTO'」異常。 – Raghav 2009-11-06 22:23:39