我正在嘗試使用泛型實體化具有公共欄位的類。
if (payload?.tableA?.name == "a")
{
Report rpt = new Report ();
ABC a = rpt.FillReport<ABC>(payload);
}
else
{
Report rpt = new Report();
BCD b = rpt.FillReport<BCD>(payload);
}
現在和ABC欄位BCD如下
class A{
pageId, paperType, printType, Volume
}
class B{
pageId, paperType, paperColor, Volume, Weight
}
所以現在我應該如何在這里使用泛型。這就是我嘗試過的。
public T FillReport<T>(DTO? dto) where T : ABC, new()
{
T report = new T();
report.pageId = dto.pageId;
report.paperType= dto.paperType;
...
}
//Works for only ABC, how Do it BCD fields.
uj5u.com熱心網友回復:
創建一個介面ISomething并使 ABC/BCD 都繼承自同一個介面:
public interface ISomething
{
pageId {get;set;}
pagerType {get;set;}
}
class A : ISomething
class B : ISomething
然后在您的方法宣告中:
public T FillReport<T>(DTO? dto) where T : ISomething, new()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510466.html
上一篇:乘以常數的通用函式
