小奋斗 - 轻松学习从此开始!
IT小奋斗群 QQ群:62017228

C#定义类型转化代码分享

operator 关键字

operator 关键字用来重载内置运算符,或提供类/结构声明中的用户定义转换。它可以定义不同类型之间采用何种转化方式和转化的结果。

operator用于定义类型转化时可采用2种方式,隐式转换(implicit)和显示转换(explicit)

public class OperatorTestDemo
{
    public static void Test()
    {
        OperatorTest mc = 1;//通过隐式装换,生成myclass对象
        Console.WriteLine(mc.Value);

        OperatorTest mc2 = new OperatorTest(2);
        Console.WriteLine((int)mc2);//显示转化,调用myclass至int的处理方法
        Console.WriteLine(mc2);//隐式转化,调用myclass至string的处理方法
    }
}
public class OperatorTest
{
    private int value;//声明value私有字段
    public int Value//声明只读属性
    {
        get { return value; }
    }
    public OperatorTest(int value)//构造函数
    {
        this.value = value;
    }

    public static implicit operator OperatorTest(int value)//隐式声明的int转OperatorTest类处理方法
    {
        return new OperatorTest(value);
    }
    public static explicit operator int(OperatorTest mc)//显示声明的OperatorTest转int类处理方法
    {
        return mc.value;
    }
    public static implicit operator string(OperatorTest mc)//隐式声明的OperatorTest转string类处理方法
    {
        return ("定义的OperatorTest类string类型转化结果");
    }
}

在利用implicit的隐式声明时,如果同时存在多个由当前类转化为其他类型数据的隐式声明的时候,可能出现2者都可以调用,编译器不知道选择哪个而出现的错误。

TypeConverter

[TypeConverter(typeof(StringToHumanTypeConverter))]
public class Human
{
    public string Name { get; set; }

    public Human Child { get; set; }
}

public class StringToHumanTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;
        else
            return base.CanConvertFrom(context, sourceType);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(string))
            return true;
        else
            return base.CanConvertTo(context, destinationType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value is string)
        {
            Human h = new Human();
            h.Name = value as string;
            return h;
        }

        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            Human h = (Human)value;
            return $"Human.Name:{(h.Name)}";
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

public static void Test()
{
    TypeConverter homanTypeConverter = TypeDescriptor.GetConverter(typeof(Human));
    if (homanTypeConverter.CanConvertFrom(typeof(string)))
    {
        Human h = (Human)homanTypeConverter.ConvertFrom("ssd");
        Console.WriteLine(h.Name);
    }
    if (homanTypeConverter.CanConvertTo(typeof(string)))
    {
        Human h = new Human() { Name= "张飞"};
        Console.WriteLine(homanTypeConverter.ConvertTo(h, typeof(string)));
    }
}

IConvertible

IFormatProvider

public class MyFormater : ICustomFormatter, IFormatProvider
{
    public object GetFormat(Type format)
    {
        if (format == typeof(ICustomFormatter))
            return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider provider)
    {
        if (format == null)
        {
            if (arg is IFormattable)
                return ((IFormattable)arg).ToString(format, provider);
            return arg.ToString();
        }
        else
        {
            if (format == "MyFormater")
            {
                return "£:" + arg.ToString();
            }
            else
            {
                if (arg is IFormattable)
                    return ((IFormattable)arg).ToString(format, provider);
                return arg.ToString();
            }
        }
    }
}

public static void Test()
{
    int i = 100;
    string printString;
    MyFormater myFormater = new MyFormater();
    printString = string.Format(myFormater, "{0}", i);
    Console.WriteLine(printString);
    printString = string.Format(myFormater, "{0:C}", i);
    Console.WriteLine(printString);
    printString = string.Format(myFormater, "{0:MyFormater}", i);
    Console.WriteLine(printString);

    Console.WriteLine(Convert.ChangeType(i, typeof(string), myFormater));
}

我来评几句
登录后评论

已发表评论数(0)