继承其他类的属性 [英] inherit properties of other class

查看:99
本文介绍了继承其他类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

公共班级1

{

prop1;

prop2;

prop3;

}



公共舱2级

{

prop4;

prop5;

prop6;

}



现在我想要class3有这些属性:



公共舱3级

{

prop1;

prop2;

prop6;

}



继承,class3隐含其他属性,我不需要它们......

要清楚,我已经在sql和每个表中创建了一些表,我的Windows窗体中的一个类。我想在DB和我的c#程序之间传输数据,我只选择查询中每个表的一些字段。为了保存查询返回的数据,我需要class3。

我尝试继承,但是我不得不初始化所有6个prop并且我不想要这个。

public class class1
{
prop1;
prop2;
prop3;
}

public class class2
{
prop4;
prop5;
prop6;
}

now I want class3 have Just these properties:

public class class3
{
prop1;
prop2;
prop6;
}

in inheritance, class3 have other properties implicitly that i don't need them...
to be clear,I have made some tables in sql and for each table, a class in my windows form Program. I want transfer data between DB and my c# program and I select just some fields of each tables in my query. to save data returned by query, I need class3.
I tried inheritance,but I had to Initialized all 6 prop's and I don't want this.

推荐答案

首先,你的代码示例将无法编译,但想法很明确。



你无法得到你想要的东西(和解决方案1)与此完全无关),因为这不是继承的工作方式。这个想法不是为了对抗OOP,而是为了让它适合你。在您的简单情况下,您只需构建适合您设计的类层次结构。例如:



First of all, your code samples won't compile, but the idea is clear.

You cannot get what you want (and Solution 1 is totally unrelated to that), because this is not how inheritance work. The idea is not to fight against OOP, but to make it work for you. In your simple case, you just need to build class hierarchy suitable to your design. For example:

class MyVeryBase {
   internal int prop1 { get; set; }
   internal int prop2 { get; set; }
}

//to get class3, you will need to add prop6:
class class3 : MyVeryBase {
   internal ulong prop6 { get; set; }
}

//to get class1, you will need to add prop3:
class class3 : MyVeryBase {
   internal string prop3 { get; set; }
}

//and class2 you can, for example, create from scratch:
class MyVeryBase {
   internal System.Text.StringBuilder prop4 { get; set; }
   internal byte prop5 { get; set; }
   internal char prop6 { get; set; }
}





如果你真的需要组合更多这两个类(例如,得到相同 prop6 ),您需要提供多重继承(阅读相关内容)。在.NET中,只能获得所谓的弱多重继承形式,只能为 interface 获取。阅读它们。



-SA



If you really need to combine more that two classes (for example, to get the same prop6), you need something to provide multiple inheritance (read about it). In .NET, you get only so called, weak form of multiple inheritance, which you can get only for interface. Read about them.

—SA


随着谢尔盖的清晰回应,我建议你阅读这篇写得很好的文章关于在C#中模拟多重继承 [ ^ ]
Along with Sergey's crisp response, I suggest you read this nicely written article about Simulating Multiple Inheritance in C#[^]


这篇关于继承其他类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆