温馨提示×

c# convert怎么转换自定义类型

c#
小樊
90
2024-07-23 04:41:05
栏目: 编程语言

要将自定义类型转换为不同的类型,您需要实现相应类型的转换方法或者重载类型转换操作符。以下是一个示例,假设我们有一个自定义类型MyType

public class MyType
{
    public int Value { get; set; }

    public MyType(int value)
    {
        Value = value;
    }
}

现在我们想要将MyType转换为int类型,可以实现一个类型转换方法:

public static class MyTypeExtensions
{
    public static int ToInt(this MyType myType)
    {
        return myType.Value;
    }
}

然后我们可以这样使用它:

MyType myType = new MyType(10);
int intValue = myType.ToInt();
Console.WriteLine(intValue); // 输出 10

另外,您还可以重载类型转换操作符来实现类型转换:

public static implicit operator int(MyType myType)
{
    return myType.Value;
}

然后我们可以这样使用它:

MyType myType = new MyType(10);
int intValue = (int)myType;
Console.WriteLine(intValue); // 输出 10

0