c# - 将自定义类型转换注入(inject) .NET 库类

标签 c# .net guid

我想在 C# 中通过 Convert.ChangeType 实现两个库类之间的转换。我不能改变这两种类型。例如在 Guid 和 byte[] 之间转换。

Guid g = new Guid();
object o1 = g;
byte[] b = (byte[]) Convert.ChangeType(o1, typeof(byte[])); // throws exception

我知道 Guid 提供了 ToByteArray() 方法,但我希望在 Guid 转换为 byte[] 时调用该方法。这背后的原因是转换也发生在我无法修改的库代码 (AseDataAdapter) 中。那么是否可以在不修改两个类的源代码的情况下定义两个类型之间的转换规则呢?

我正在试验 TypeConverter,但似乎也不起作用:

Guid g = new Guid();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Guid));
byte[] b2 = (byte[])tc.ConvertTo(g, typeof(byte[])); // throws exception

变量 tc 被设置为不支持转换为 byte[] 的 System.ComponentModel.GuidConverter。我可以为同一个类设置两个 TypeConverter 吗?即使可以,难道我不需要在类的源代码前添加一个属性来分配 TypeConverter 吗?

谢谢

最佳答案

您可以使用 TypeDescriptor.AddAttributes 更改已注册的 TypeConverter;这与 Convert.ChangeType 不太一样,但它可能就足够了:

using System;
using System.ComponentModel;
static class Program
{
    static void Main()
    {
        TypeDescriptor.AddAttributes(typeof(Guid), new TypeConverterAttribute(
            typeof(MyGuidConverter)));

        Guid guid = Guid.NewGuid();
        TypeConverter conv = TypeDescriptor.GetConverter(guid);
        byte[] data = (byte[])conv.ConvertTo(guid, typeof(byte[]));
        Guid newGuid = (Guid)conv.ConvertFrom(data);
    }
}

class MyGuidConverter : GuidConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(byte[]) || base.CanConvertFrom(context, sourceType);
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(byte[]) || base.CanConvertTo(context, destinationType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value != null && value is byte[])
        {
            return new Guid((byte[])value);
        }
        return base.ConvertFrom(context, culture, value);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(byte[]))
        {
            return ((Guid)value).ToByteArray();
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

关于c# - 将自定义类型转换注入(inject) .NET 库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606854/

相关文章:

.net - 检测到冲突的ASP.NET Web页版本:指定的版本是 “1.0.0.0”,但是bin中的版本是ASP.MET MVC 3中的 “2.0.0.0”

c# - WebSockets 我需要什么 'using' 指令

c# - 有没有办法强制派生类实现抽象类或嵌套在基类中的接口(interface)?

c# - 使用 Entity Framework 的 SqlBulkCopy(和更新)

.net - 使用 .Net 校正图像歪斜

java - 128 位(16 字节)GUID 被压缩为多少位或字节?

Delphi 7 tguid 比较

sql - 当数据库被移动到另一个服务器/实例时如何识别它

c# - 让 FocusManager 等到数据绑定(bind)完成?

c# - 在 Windows 8 上对 Facebook 执行 Get 请求