如何在 C# 中从派生类实例调用基方法?

che*_*hty 4 c# inheritance

我有 C# 代码、基础代码class A和派生代码class B

public class A
{
    public virtual void print() {Console.WriteLine("a"); }
}
public class B:A
{
    public override void print() { Console.WriteLine("b"); }
}

static void Main(string[] args)
{
    A a= new B();
    //In c++ I can use .Base:: to call base method from derived class instance
    a.Base::print();
}
Run Code Online (Sandbox Code Playgroud)

我无法修改这两个类,而且我不知道在 C# 中可以做什么,有什么建议吗?


此外,感谢大家参与这次讨论,我想澄清为什么我需要这种行为:

在.net框架中,我们有一个接口IPostBackDataHandler来处理回发。里面有一个方法

public bool LoadPostData( string postDataKey, NameValueCollection postCollection )
Run Code Online (Sandbox Code Playgroud)

当我实现它并测试时,我发现有时给定的postCollection回发类型是NameValueCollection,而其他时候它是HttpValueCollection ( NameValueCollection的派生类)

然后,如果它是HttpValueCollection的类型,当我从中获取项目时,例如。postCollection['ControlID']并且我在此控件中输入html , HttpValueCollection.get_item()将始终验证输入并将其视为缺陷。虽然NameValueCollection.get_item()不会

我不希望它自动进行验证,至少应该决定是否应该验证它,不是吗?

noc*_*ame 6

无法从派生类外部访问基方法。您可以在派生类中编写一个方法来调用基方法,如下所示:

public class B : A
{
    public override void print() { Console.WriteLine("B"); }

    public void basePrint() { base.print(); }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以用户Reflection获取基本方法定义并调用它,但它相当难看。以下是创建DynamicMethod调用基本print方法的方法:

// Get MethodInfo of the base method
var methodInfo = typeof(A).GetMethod("Print", BindingFlags.Instance | BindingFlags.Public);

// Create DynamicMethod based on the methodInfo
var dynamicMethod = new DynamicMethod("BasePrint", methodInfo.ReturnType, new[] { methodInfo.DeclaringType }, methodInfo.DeclaringType);
// Create ILGenerator for the dynamic method
var il = dynamicMethod.GetILGenerator();

// Emit argument with index 0 - DeclaringType
il.Emit(OpCodes.Ldarg_0);
// Emit method call
il.EmitCall(OpCodes.Call, methodInfo, null);
// Emit method return value
il.Emit(OpCodes.Ret);

// Invoke method with target...
var b = new B();
dynamicMethod.Invoke(null, new object[] {b});

// ... or create a delegate and invoke method without target
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Invoke();
Run Code Online (Sandbox Code Playgroud)

请注意,它仅适用于无参数方法。如果你想调用带有参数的方法,你必须将它们的类型放入数组中DeclaringType,然后发出所有它们。此外,您还必须创建类型的委托Action<parameterTypes,或者Func<returnType, parameterTypes>如果该方法返回某些内容。