我很惊讶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}");
}
}
产生输出:
可选参数的值为False
可选参数的值为True
我的问题是:是否可以在没有默认值或“ overridable”的接口中定义一个可选参数,因此对保存在接口类型变量中的实例调用方法使用在实现此接口的类中定义的可选值?] >
我很惊讶C#使用值作为接口的可选方法参数,而不是来自实现此接口的类。例如:使用系统;公共类程序{private static ...
如果您了解内部如何处理可选参数:在编译过程中内联它们,这就不足为奇了。