在 C# 的扩展方法中为调用者变量赋值

Posted

技术标签:

【中文标题】在 C# 的扩展方法中为调用者变量赋值【英文标题】:Assign value to caller variable in extension method in C# 【发布时间】:2013-10-10 02:14:24 【问题描述】:

我遇到了扩展方法的问题。我做了一个通用的扩展方法来获取 QueryString。我用特定类型的变量调用该方法,QueryString 附带了哪种类型的数据。我的扩展方法如下。

public static class my

    public static void GetQueryString<T>(this T caller, string queryString)
    
        if (HttpContext.Current.Request.QueryString[queryString] != null)
        
            T type = (T)Convert.ChangeType(HttpContext.Current.Request.QueryString[queryString], typeof(T));
            caller = type;
        
    

    public static void GetQueryString(this Employee caller)
    
        caller.ID = 23;
    

我想从查询字符串中获取字符串值,因为我声明了一个字符串变量,然后调用扩展方法。我想在“t1”变量中获取查询字符串值。

 string t1 = string.Empty;
 t1.GetQueryString("name");

但是该值没有出现在调用者变量中。同样的事情是使用与 Employee 对象相关的扩展方法,但我想在原始类型中获取价值。如果有人对此有想法,请与我分享。提前致谢。

【问题讨论】:

你不能改变caller的值,因为是val传递的,在c#中你不能通过ref传递扩展方法的this参数。您的第二种方法有效,因为您没有明显更改 caller 的值。 我真的同意你的观点,val 传递的内容没有改变,但扩展方法也扩展了原始类型。然后我想知道有没有这样做的余地。如您所见,上面的 Employee 对象被赋值给 ID 属性。 是的,但caller 的值没有改变,它指向同一个对象。作为旁注,VB.NET 允许您通过 ref 传递参数。 实际上我的目的是知道如果员工正在调用此函数,那么它会在 ID 中分配值,但如果我创建了一个 int 变量并通过 this 调用而不分配任何值并且都使用“this”关键字在扩展参数中。 【参考方案1】:

你可以这样做:

public static T GetQueryString<T>(this T caller, string queryString)

    if (HttpContext.Current.Request.QueryString[queryString] != null)
    
        T type = (T)Convert.ChangeType(HttpContext.Current.Request.QueryString[queryString], typeof(T));

        return type;
    


string t1 = string.Empty;
t1 = t1.GetQueryString("name"); // return the value and reassign

但我没有测试GetQueryString 方法。 我能想到的唯一方法是,但没有扩展方法:

public static T GetQueryString<T>(ref T caller, string queryString)

    if (HttpContext.Current.Request.QueryString[queryString] != null)
    
        T type = (T)Convert.ChangeType(HttpContext.Current.Request.QueryString[queryString], typeof(T));

        return type;
    


GetQueryString(ref t1, "name");

【讨论】:

亲爱的,我也可以返回查询字符串的值,但我不想这样做,因为为此我必须分配相同的变量,如 t1=t1.GetQueryString("name");我不想这样做。

以上是关于在 C# 的扩展方法中为调用者变量赋值的主要内容,如果未能解决你的问题,请参考以下文章

解读经典《C#高级编程》第七版 Page100-107.继承.Chapter4

c#中函数参数中的this(扩展方法)

c#中函数参数中的this(扩展方法)

如何在 C# 中为电子邮件设置 Outlook 扩展属性?

我们如何在 TypeScript 中为非全局接口创建扩展方法?

在 C# 中重载复合赋值运算符的简单方法?