c# - 使用接口(interface)将对象从一种类型转换为另一种类型?

标签 c# .net .net-3.5 interface copying

假设我有两个具有相同接口(interface)的类:

interface ISomeInterface 
{
    int foo{get; set;}
    int bar{get; set;}
}

class SomeClass : ISomeInterface {}

class SomeOtherClass : ISomeInterface {}

假设我有一个代表 SomeClass 的 ISomeInterface 实例。有没有一种简单的方法可以将其复制到 SomeOtherClass 的新实例中,而无需手动复制每个成员?

更新:郑重声明,我没有尝试将 SomeClass 的实例转换为 SomeOtherClass 的实例。我想做的是这样的:

ISomeInterface sc = new SomeClass() as ISomeInterface;
SomeOtherClass soc = new SomeOtherClass();

soc.foo = sc.foo;
soc.bar = soc.bar;

我只是不想手动为每个对象执行此操作,因为这些对象具有很多属性。

最佳答案

您可以在每个类中创建隐式运算符来为您进行转换:

public class SomeClass
{
    public static implicit operator SomeOtherClass(SomeClass sc)
    {
        //replace with whatever conversion logic is necessary
        return new SomeOtherClass()
        {
            foo = sc.foo,
            bar = sc.bar
        }
    }

    public static implicit operator SomeClass(SomeOtherClass soc)
    {
        return new SomeClass()
        {
            foo = soc.foo,
            bar = soc.bar
        }
    }
    //rest of class here
}

然后 SomeOtherClass soc = sc; 反之亦然。

关于c# - 使用接口(interface)将对象从一种类型转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/303555/

相关文章:

c# - 我可以使用 'object' 关键字使方法更通用吗?

c# - Wix C# 自定义操作根本不执行

c# - 将 IsMouseOver 绑定(bind)到 UserControl 中的 ViewModel

.net - 我什么时候应该使用编译的 Regex 与解释的?

c# - 使用 LINQ 将 List<U> 转换为 List<T>

c# - ExpressionTree 重写 - 参数 'x' 不在范围内

c# - 异步远程调用

c# - 使用网络摄像头捕获视频并使用 C# 保存为 avi

C# (.NET 3.5) 有没有办法得到这个函数名?

c# - 请帮忙。创建线程并等待完成