由于多重继承是不好的(它使源更复杂),C#不直接提供这样的模式.但有时候拥有这种能力会有所帮助.
例如,我能够使用接口和三个类来实现缺少的多继承模式:
public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class First:IFirst
{
public void FirstMethod() { Console.WriteLine("First"); }
}
public class Second:ISecond
{
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond: IFirst, ISecond
{
First first = new First();
Second second = new Second();
public void FirstMethod() { first.FirstMethod(); }
public void SecondMethod() { second.SecondMethod(); }
}
Run Code Online (Sandbox Code Playgroud)
每次我向其中一个接口添加方法时,我都需要更改类FirstAndSecond.
有没有办法将多个现有类注入一个新类,就像在C++中一样?
也许有一种使用某种代码生成的解决方案?
或者它可能看起来像这样(假想的c#语法):
public class FirstAndSecond: IFirst from First, ISecond …Run Code Online (Sandbox Code Playgroud) 在WPF应用程序中,我的类层次结构遇到了一些问题.这是将两个继承树合并在一起的问题之一,如果没有多重继承,就无法找到任何合理的方法来使继承顺利运行.我想知道是否有人有任何明智的想法让这种系统工作,而不会让它无法遵循或调试.
我是一名低级工程师,所以我的第一个想法总是,"哦!我只是用原生C++写一些这些类,并在外部引用它们!然后我可以让我所有的老派OO好玩!" 唉,当你需要从托管控件继承时,这没有用...
请允许我显示当前投影类图的片段:
____________________________________ _____________________________________
| CustomizableObject | | System.Windows.Controls.UserControl |
|____________________________________| |_____________________________________|
| string XAMLHeader() | ?
| string XAMLFooter() |?--? |
| CustomizableObject LoadObject() | \ |
| <Possible other implementations> | \ |
|____________________________________| \ |
? ? \ |
| | \ |
| | \ |
_________________ ______________________ \ _____________________
| SpriteAnimation | | SpriteAnimationFrame | ?---| CustomizableControl |
|_________________| |______________________| |_____________________|
? ?
| |
| |
________ _____________
| Sprite …Run Code Online (Sandbox Code Playgroud) 我想从几个旧的测试类中使用一些方法到我正在构建的新类中.不幸的是,C#不支持多重继承.如何重用这些旧类中的代码?我只是将它们创建为成员对象吗?或者我还有其他选择吗?
更新:所以这里的每个人都告诉我,我只需要重新开始我如何设计课程(顺便说一句,谢谢大家的优秀答案!).接下来,我开始对战略模式进行广泛阅读.我想创建从抽象基类继承的行为类(或策略类).然后,Candidate类将具有不同抽象基类/类的属性作为Type行为或策略.也许是这样的:
public abstract class SalaryStrategy {
public abstract decimal Salary { get; set; }
public abstract decimal Min { get; set; }
public abstract decimal Mid { get; set; }
public decimal CompaRatio {
get {
if (this.Mid == 0) { return 0; }
else { return this.Salary / this.Mid; }
}
}
}
public class InternalCurrentSalaryStrategy {
public override decimal Salary { get; set; }
public override decimal Min {
get { return this.Salary * …Run Code Online (Sandbox Code Playgroud) c# inheritance code-reuse design-patterns multiple-inheritance
我打算使用Kohana的加密类,但是有更好更安全的双向处理方式吗?我希望我的用户能够发送他们以前密码的请求,而不是给他们重置密码.
您可以建议的任何算法或库?特别是在PHP?
c# ×4
inheritance ×3
.net ×1
.net-3.5 ×1
code-reuse ×1
interface ×1
oop ×1
php ×1
reusability ×1
security ×1