接口的可选参数 [英] Optional parameters for interfaces

查看:20
本文介绍了接口的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 c# 4.0 -- 构建一个接口和一个实现该接口的类.我想在接口中声明一个可选参数并将其反映在类中.所以,我有以下几点:

Using c# 4.0 -- building an interface and a class that implements the interface. I want to declare an optional parameter in the interface and have it be reflected in the class. So, I have the following:

 public interface IFoo
 {
      void Bar(int i, int j=0);
 }

 public class Foo
 {
      void Bar(int i, int j=0) { // do stuff }
 }

这个可以编译,但是看起来不对.接口需要有可选参数,否则它不会在接口方法签名中正确反映.

This compiles, but it doesn't look right. The interface needs to have the optional parameters, because otherwise it doesn't reflect correctly in the interface method signature.

我应该跳过可选参数而只使用可空类型吗?或者这会按预期工作而没有副作用或后果吗?

Should I skip the optional parameter and just use a nullable type? Or will this work as intended with no side effects or consequences?

推荐答案

您可以考虑 pre-optional-parameters 替代方案:

You could consider the pre-optional-parameters alternative:

public interface IFoo
{
    void Bar(int i, int j);
}

public static class FooOptionalExtensions
{
    public static void Bar(this IFoo foo, int i)
    {
        foo.Bar(i, 0);
    }
}

如果您不喜欢新语言功能的外观,则不必使用它.

If you don't like the look of a new language feature, you don't have to use it.

这篇关于接口的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆