![](/img/trans.png)
[英]Cannot create an instance of the abstract class or interface, but it is not an abstract class and it's not an interface?
[英]Create interface + Class wrapper from abstract references
我有以下對象與以下字段:
class ObjectA
{
float progress;
bool isDone;
}
class ObjectB
{
bool canceled;
}
我想創建將被綁定的ObjectC
,並使ObjectA
和ObjectB
字段progress
, isDone
和canceled
。
我該怎么辦?
這是通過dynamic
類型還是某些Interface + ClassWrapper組合實現的?
無法更改ObjectA
和ObjectB
類型,類,簽名等。 它們按原樣給出。
c#中沒有類似於多類繼承的東西。 做這種事情的最好方法是為每個行為聲明接口:
interface IA
{
float Progress {get;}
bool IsDone {get;}
}
interface IB
{
bool IsCanceled{get;}
}
也許是第三個聚合前兩個:
interface IC : IA , IB
{
}
並在一個類中實現。
class C : IC
{
public float Progress { get; set; }
public bool IsDone { get; set; }
public bool IsCanceled { get; set; }
}
然后你必須記住編程接口而不是類:
class SomeClass
{
//If only IA features are required
void DoSTH(IA c){}
}
你可以通過作文來做到這一點:
public class ObjectC
{
public ObjectA ProgressInfo { get; set; }
public ObjectB CanceledInfo { get; set; }
}
或通過接口:
public interface IProgressable
{
float Progress { get; }
bool IsDone { get; }
}
public interface ICancelable
{
bool Canceled { get; }
}
那么你可以讓你的新類實現兩個接口:
public class ObjectC : IProgressable, ICancelable
{
...
}
您正在尋找C#不支持的multiple inheritance
。
一種解決方案是使用接口,但它需要您多次實現代碼:
public interface IFoo1
{
float Progress { get; set; }
bool IsDone { get; set; }
}
public interface IFoo2
{
bool Canceled { get; set; }
}
public abstract class ObjectA : IFoo1
{
public float Progress { get; set; }
public bool IsDone { get; set; }
}
public abstract class ObjectB : IFoo2
{
public bool Canceled { get; set; }
}
public class ObjectC : IFoo1, IFoo2
{
public float Progress { get; set; }
public bool IsDone { get; set; }
public bool Canceled { get; set; }
}
您想要的是通過常規方式無法實現的,因為您的字段是私有的,因此對於ObjectA
和ObjectB
之外的任何代碼都無法訪問。
唯一的方法 - 我根本不建議,因為它打破了封裝 - 將使用反射來訪問這些成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.