在类型为< T>的类型T的成员变量上调用扩展方法 [英] Calling an extension method on a member variable of type T of class<T>

查看:107
本文介绍了在类型为< T>的类型T的成员变量上调用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定扩展方法如下:

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


$ / code $ / pre

和类:

  public class Field< T> 
{
公共T值;

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




$ b我想要做以下事情, t相当数字:

  public class Foo 
{
public Field< Guid> UID;

public Foo()
{
//假定StringWriter对象sw;
uid.Serialize(sw);


$ / code>

显然现实生活中的情况比较复杂,这是只是一个简单的例子。

编辑



编译错误: p>

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



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

解决方案

这是不可能的,因为 T 在编译时并不知道它是否是 Guid

但你可以这样做

 公共类GuidField:Field< Guid> 
{
public override void Serialize(StringWriter sw _)//假设我们已经使基类方法变为虚拟
{
value.Serialize(sw_);




$ b $ p
$ b

这样做可以,因为c#编译器知道 value 在编译时是 Guid



以下方法可行,但它会打败泛型的观点。不建议也。
举例说明如何做一个例子

  public void Serialize(StringWriter sw_)
{
if(typeof(T)== typeof(Guid))
{
((Guid)(object)value).Serialize(sw_);
}
}


Given extension method below:

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

and the class:

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.

EDIT

Compiler errors:

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

error CS1929: Instance argument: cannot convert from 'T' to 'System.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_);
    }
}

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_);
    }
}

这篇关于在类型为&lt; T&gt;的类型T的成员变量上调用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆