简体   繁体   English

如何为没有具体类型但有接口的参数赋予默认值

[英]How to give a default value to a parameter which has no concrete type but an interface

I have this function doSomething.我有这个 function 做某事。 99% of the time it take the same arg. 99% 的时间需要相同的参数。 I would like to create a default argument.我想创建一个默认参数。 But the type of the argument is a interface但是参数的类型是接口

    public static void doSomething(Itype arg=new classWhichImplementItype())
    {
        //do something
    }

Default paramter value for arg must be a compile time constant. arg 的默认参数值必须是编译时间常数。

How can I do我能怎么做

Default arguments must be compile-time constants.默认 arguments 必须是编译时常量。 So, use overloads:所以,使用重载:

public static void doSomething()
{
    doSomething(new classWitchImplementItype());
}

public static void doSomething(Itype arg)
{
    //do something
}

In recent versions of C#, you can also use the arrow syntax for the overload:在最新版本的 C# 中,您还可以使用箭头语法进行重载:

public static void doSomething() => doSomething(new classWitchImplementItype());

Try this:尝试这个:

public static void doSomething(Itype arg=null)
    {
          if (arg==null) arg=new classWitchImplementItype();

        //do something
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM