【发布时间】:2020-04-07 13:13:52
【问题描述】:
我在这里搜索过类似的问题,但找不到解决问题的方法。 MyClass 保存多个数据并在不同类型之间进行一些类型转换。
我怎样才能避免这个错误:
“字符串”类型的值不能用作默认参数 因为没有标准转换类型 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"));
}
}
【问题讨论】:
-
您不能将字符串分配给类的对象...为什么要这样做?类类型的参数不能有默认参数值。
-
您可能想为您的班级添加implicit conversion operator:
public static explicit operator MyClass(string s)
标签: c# .net type-conversion