在class< T& gt;的类型T的成员变量上调用扩展方法.

在class< T& gt;的类型T的成员变量上调用扩展方法.

问题描述:

给出以下扩展方法:

public static class Ext
{
    public static void Serialize(this Guid guid_, StringWriter sw_)
    {
        sw_.Write(guid_.ToString("B"));
    }
}

和班级:

public class Field<T>
{
    public T value;

    public void Serialize(StringWriter sw_)
    {
        value.Serialize(sw_);
    }
}

我想执行以下操作,但无法完全解决:

I would like to do the following, but can't quite figure it out:

public class Foo
{
    public Field<Guid> uid;

    public Foo()
    {
        // assume StringWriter object sw;
        uid.Serialize(sw);
    }
}

显然,现实生活中的情况更为复杂,这只是一个简单的例子.

Obviously real-life situation is more complicated, this is just a bare-bones example.

编辑

编译器错误:

错误CS1928:'T'不包含'Serialize'的定义,最佳扩展方法重载'Ext.Serialize(System.Guid,StringWriter)'具有一些无效的参数

error CS1928: 'T' does not contain a definition for 'Serialize' and the best extension method overload 'Ext.Serialize(System.Guid, StringWriter)' has some invalid arguments

错误CS1929:实例参数:无法从'T'转换为'System.Guid'

error CS1929: Instance argument: cannot convert from 'T' to 'System.Guid'

这是不可能的,因为在编译时不确定 T 是否为 Guid

It is not possible because T is not certainly known at compile time whether it is Guid or not.

但是你可以做这样的事情

But you can do something like this

public class GuidField : Field<Guid>
{
    public override void Serialize(StringWriter sw_)//Assume we have made base class method virtual
    {
        value.Serialize(sw_);
    }
}

这是可行的,因为c#编译器在编译时知道 value Guid .


遵循方法将行得通,但将挫败泛型"的观点.不推荐也.为了展示如何做,我举一个例子

This works, since c# compiler knows value is Guid at compile time.


Following way will work but it will defeat the point of "Generics". Not recommended also. To show how to do I give an example
public void Serialize(StringWriter sw_)
{
    if (typeof (T) == typeof (Guid))
    {
        ((Guid)(object)value).Serialize(sw_);
    }
}