我惊讶地发现,C# 在接口的可选方法参数中使用的是值,而不是实现此接口的类。例如:
using System;
public class Program
{
private static IMyInterface instance;
public static void Main()
{
instance = new MyClass();
instance.PrintOpt();
((MyClass)instance).PrintOpt();
}
}
public interface IMyInterface
{
void PrintOpt(bool opt = false);
}
public class MyClass : IMyInterface
{
public void PrintOpt(bool opt = true)
{
Console.WriteLine($"Value of optional argument is {opt}");
}
}
生成输出:
可选参数值为假
可选参数值为真
我的问题是:是否可能在接口中定义一个无默认值或“可重写”的可选参数,以便在使用实现该接口的类定义的可选参数值时,对保存在接口类型变量中的实例调用方法时使用该值?