c# - 绑定(bind)两个不同类但具有相似属性的对象

标签 c#

在 C# 中是否可以绑定(bind)两个不同类但具有相似属性的对象?

例如:

class Program
{
    static void Main(string[] args)
    {
        test t = new test();

        test2 t2 = new test2();
    }
}

public class test
{
    public int Number { get; set; }
}

public class test2
{
    public int Number { get; set; }
}

那么可以用某种方式说t = t2吗?

最佳答案

如果您不关心使用哪个接口(interface)实现,则可以让两个类都实现一个接口(interface)。

例如:

class Program
{
    static void Main(string[] args)
    {
        INumber t = new test();

        INumber t2 = new test2();
    }
}

public class test : INumber
{
    public int Number { get; set; }
}

public class test2 : INumber
{
    public int Number { get; set; }
}

public interface INumber
{
    int Number { get; set; }
}

接口(interface)是一种契约,它提供了实现类必须定义的属性和方法的定义。您可以阅读更多内容interfaces here .

当您的类实现共享接口(interface)时,您可以将一种类型隐式转换为另一种类型,如上面的示例所示。

关于c# - 绑定(bind)两个不同类但具有相似属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257861/

相关文章:

c# - 在服务中使用 A3 证书

c# - 未调用全局异常处理程序

c# - 设置 DataGridView 单元格值并添加新行

c# - 我应该如何编写 XML 注释以避免在摘要和返回标记之间重复自己?

c# - 查找调用的方法

c# - 从 C# FtpWebRequest FTP 代码更改为 SFTP

c# - 将执行的 Sql 保存在表中

c# - WPF 中的文本呈现

c# - C# 中的 Windows .NET 程序与 C++ 中的 Linux 程序之间的 TCP

c# - 无法在自定义验证器中返回自定义错误消息