简体   繁体   English

C#:有一个“可选”参数,默认情况下使用所需参数的值

[英]C#: Have a “Optional” Parameter that by default uses the value of a required parameter

How can i implement a "optional" parameter to a function such that when endMarker is not given, i will use the value from a required parameter startMarker ? 如何为函数实现“可选”参数,以便在未给出endMarker时,我将使用所需参数startMarker的值? i currently use a nullable type and check if endMarker is null i set it to startMarker 我目前使用可空类型并检查endMarker是否为null我将其设置为startMarker

protected void wrapText(string startMarker, string? endMarker = null) { 
    if (endMarker == null)
        endMarker = startMarker; 
}

but the problem now is i get an error saying it cannot cast string? 但现在的问题是我得到一个错误,说它不能投射string? into string 成为string

(string)endMarker

how can i cast endMarker to a string so i can use it? 如何将endMarker转换为string以便我可以使用它? or is there a better way of implementing this? 还是有更好的方法来实现这个?

This will work: 这将有效:

protected void wrapText(string startMarker, string endMarker = null) { 
    if (endMarker == null)
        endMarker = startMarker; 
}

In other words: remove the question mark from the string? 换句话说:从string?删除问号string? . System.String is a reference type and can already be null . System.String是一个引用类型,可以为null The Nullable<T> structure can only be used on value types. Nullable<T>结构只能用于值类型。

You need to overload the method to have a call without the "optional" parameter. 您需要重载方法以在没有“可选”参数的情况下进行调用。 Then in this method you just call the normal method passing in the same parameter twice: 然后在这个方法中你只需要调用普通方法两次传递相同的参数:

protected void wrapText(String startMarker, String endMarker) 
{  
    // do stuff 
} 


protected void wrapText(String startMarker) 
{  
    wrapText(startMarker, startMarker);
} 

Can't you just do something like this: 你不能只做这样的事情:

protected void wrapText(string startMarker, string? endMarker = null) { 
    if (endMarker == null)
    {
        endMarker = "foo";
        endMarker = startMarker;
    }
}

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

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