我在这里搜索过类似的问题,但找不到解决我的问题的方法。 MyClass 保存多个数据并在不同类型之间进行一些类型转换。
如何避免此错误:
A value of type 'string' cannot be used as default parameter because there are no standard conversions to type Program.MyClass?
我尝试过 Func 并声明了多个函数重载,以便能够传递多个参数并处理默认参数。应该有更好的方法来实现这一目标。希望你能帮忙。
为了澄清我的问题,我编写了这段代码:
using System;
public class Program
{
public class MyClass {
public string Value { get; set; }
public MyClass()
{
Value = "";
}
public MyClass(string s)
{
Value = s;
}
public override string ToString()
{
return this.Value;
}
}
// Causes CS1750
// A value of type 'string' cannot be used as default parameter
// because there are no standard conversions to type 'Program.MyClass'
public static string test2(string a, MyClass b = " with default text")
{
return a + b;
}
public static string test(string a, string b = " with default text")
{
return a + b;
}
public static void Main()
{
Console.WriteLine(test("test1"));
Console.WriteLine(test("test1", " with my text"));
}
}
最佳答案
这不太可能。正如错误消息所述,您需要标准转换: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#standard-conversions
我们能做的就是为类定义一个隐式转换运算符:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators
就您而言,它会是这样的:
public static implicit operator MyClass(string val) => new MyClass(val);
并将您的测试方法替换为如下内容:
public static string test(string a, MyClass b = null)
{
b = b ?? " with default text";
return a + b;
}
另请注意,如果仅提供一个参数,则两种测试方法都具有相同的签名,因此编译器将不知道使用哪一种,请删除第二个测试方法的默认值。
关于c# - 如何将类作为可选参数传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59333495/