c# - 如何将类作为可选参数传递给方法?

标签 c# .net type-conversion

我在这里搜索过类似的问题,但找不到解决我的问题的方法。 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/

相关文章:

c# - 如何从谓词对象中删除重复项?

asp.net - 除非物理文件存在,否则 Global.asax Application_BeginRequest 不会触发 - 404

c++ - 转换函数/运算符,静态解析函数还是转换构造函数?

c++ - 询问变量在 C++ 中是什么数据类型

c# - SQL Server 2008 FTS 问题,最好的选择

c# - 在 WPF 应用程序中使用 MVVM/MVVMLight 时如何与 UI 元素交互

c# - 如何使用c#将字符串与另一个字符串进行比较

c# - 将 "[{a},{b},{c}]"拆分为字符串数组 "a,b,c"的最佳方法是什么

C# WPF - 窗口中的黑线

PHP - 如何将矩形图像转换为方形图像?