在 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/