【发布时间】:2021-11-17 22:20:31
【问题描述】:
我正在寻找在(抽象)基类中提供方法的最佳方式,所有继承类都应该能够使用该方法。
此方法需要引用继承类型的字段和属性。
有没有办法提供这样一个不需要我的原型方法:
- 传递对每个有问题的继承实例的引用
- 在每个继承类上实现一个方法,它将对自身的引用传递给基类的方法
- 为实现类编写扩展方法
上述所有工作,但在他们自己的方式似乎有些不方便和不优雅。
下面是一个例子,我实现了上面三个引用继承类的方法:
using System;
namespace Test
{
public abstract class BaseClass
{
public void ReferenceInheriting(object InheritingInstance)
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " + InheritingInstance.GetType().Name);
}
}
public class Inheriting : BaseClass
{
public void MakeUseOfBaseClassImplementation()
{
base.ReferenceInheriting(this);
}
}
public static class Extensions
{
public static void BeAvailableForAllImplementing(this BaseClass Inh)
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " + Inh.GetType().Name);
}
}
class program
{
public static void Main(string[] args)
{
Inheriting inh = new Inheriting();
Console.WriteLine("Method 1: Calling the inherited method from an inheriting instance, passing a reference to the instance:");
inh.ReferenceInheriting(inh);
Console.WriteLine("Method 2: Implementing call to the base class's method in own class:");
inh.MakeUseOfBaseClassImplementation();
Console.WriteLine("Method 3: Extension method for all implementing classes:");
inh.BeAvailableForAllImplementing();
}
}
}
这三种方法都产生相同的输出,但都有缺点。
缺少解析来电者信息,有没有其他方法可以做到这一点?
当然这没什么大不了的,但我有兴趣让这个方法尽可能地对用户友好,无论是实现继承还是调用。
谢谢!
【问题讨论】:
-
为什么要在这里使用反射?如果
BaseClass有合法用途,为什么不声明getMe? -
附带说明:如果您遵循正常的命名约定,即使对于示例代码,它也会很有帮助。对于阅读问题或试图回答您的人来说,任何非常规的内容都会分散您的注意力。
-
@JonSkeet 您具体指的是命名约定的哪些方面?当然,名字可能有点长,但我认为他们描述了我对他们的期望,好吧
-
@BenPhilipp:
reflectInheriting应该是ReflectInheriting,getMe应该是GetMe,等等。我认为问题不在于长度,而在于大小写。它也让我有点失望。 -
@ThomasBonini 哦!我看到了
标签: c# .net inheritance