Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建接口&x2B;来自抽象引用的类包装器_C#_.net - Fatal编程技术网

C# 创建接口&x2B;来自抽象引用的类包装器

C# 创建接口&x2B;来自抽象引用的类包装器,c#,.net,C#,.net,我有以下具有以下字段的对象: class ObjectA { float progress; bool isDone; } class ObjectB { bool canceled; } 我想创建ObjectC,它将绑定到,并具有ObjectA和ObjectB字段进度,isDone和取消 我怎么能做这样的事 这是否可以通过动态类型或某些接口+类包装组合实现 ObjectA和ObjectB类型、类、签名等不能更改。它们是按原样给出的。在c#中没有类的多基继承。最好的方

我有以下具有以下字段的对象:

class ObjectA
{
    float progress;
    bool isDone;
}

class ObjectB
{
    bool canceled;
}
我想创建
ObjectC
,它将绑定到,并具有
ObjectA
ObjectB
字段
进度
isDone
取消

我怎么能做这样的事

这是否可以通过
动态
类型或某些接口+类包装组合实现


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
{
    ...
}
然后,您可以让新类实现两个接口:

public interface IProgressable
{
    float Progress { get; }

    bool IsDone { get; }
}

public interface ICancelable
{
    bool Canceled { get; }
}
public class ObjectC : IProgressable, ICancelable
{
    ...
}

您正在查找C#不支持的
多重继承

一种解决方案是使用接口,但它要求您多次实现代码:

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
之外,任何代码都无法访问这些字段


唯一的方法是使用反射来访问这些成员。我不建议这样做,因为这会破坏封装。请通过缩进行正确发布代码片段。什么是“绑定到”?我的意思是我不能更改ObjectA和ObjectB类。因此无法向其添加UInterface