【问题标题】:Assign value to caller variable in extension method in C#在 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”关键字在扩展参数中。

标签: c# extension-methods


【解决方案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");我不想这样做。
猜你喜欢
  • 2022-06-10
  • 2012-04-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多