2010-09-20 154 views
2

我只是想编写以下扩展方法:扩展方法可以修改扩展类的值吗?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace _4Testing 
{ 
    static class ExtensionMethods 
    { 
     public static void AssignMe(this int me, int value) 
     { 
      me = value; 
     } 
    } 
} 

但它不工作,我的意思是,我可以使用扩展方法来扩展从班改变值?我不想将void返回类型更改为int,只是更改扩展类的值。在此先感谢

回答

5

您的示例使用int,这是一个值类型。在这种情况下,类是引用类型,行为有点不同。

虽然您可以制作另一个参考文件,如AssignMe(this MyClass me, MyClass other),但该方法可以在参考副本上工作,因此如果您将other指定为me,它只会影响参考的本地副本。

另外,请记住,扩展方法只是变相的静态方法。即他们只能访问扩展类型的公共成员。

public sealed class Foo { 
    public int PublicValue; 
    private int PrivateValue; 
} 

public static class FooExtensions { 
    public static void Bar(this Foo f) { 
     f.PublicValue = 42; 

     // Doesn't compile as the extension method doesn't have access to Foo's internals 
     f.PrivateValue = 42; 
    } 
} 
+0

酷布赖恩!现在让我回到我的IDE继续更改我的代码。 – 2010-09-20 13:13:31

0

拉蒙你真正需要的是在第一个ref修饰符(即诠释我)扩展方法的参数,但C#不允许在具有“这个”修饰符参数ref修饰符。

[更新] 对于您的值类型的扩展方法的特定情况,应该没有解决方法。如果你被允许做你想做的事情,那么你所要求的就是“减少和消除荒谬”;考虑C#语句:
5.AssignMe(10);
......现在你认为它应该做什么?你想分配10到5? 运算符重载也无济于事。

+1

所以,我的问题是寻找解决方法,你有一个吗?无论如何感谢 – 2010-09-20 13:10:15

1
// a work around for extension to a wrapping reference type is following .... 

using System; 


static class Program 
{ 

    static void Main(string[] args) 
    { 


    var me = new Integer { value = 5 }; 
    int y = 2; 

    me.AssignMe(y); 

    Console.WriteLine(me); // prints 2 

    Console.ReadLine(); 
    } 

    public static void AssignMe(this Integer me, int value) 
    { 

     me.value = value; 
    } 


} 

    class Integer 
    { 


     public int value { get; set; } 

     public Integer() 
    { 
     value = 0; 
    } 

    public override string ToString() 
    { 
     return value.ToString(); 
    } 

    } 
+0

好mumtaz!最后我实施了类似的解决方案。 – 2010-09-21 15:17:21

0

这是一个旧的帖子,但我遇到了类似的问题,试图为String类实现扩展器。

我原来的代码是这样的:

public static void Revert(this string s) 
{ 
    char[] xc = s.ToCharArray(); 
    s = new string(xc.Reverse()); 
} 

通过使用我创建一个新的对象的新的关键字和S是不是按引用传递它不会被修改。

我改成它提供了一个解决方案,拉蒙的问题如下:

public static string Reverse(this string s) 
{ 
    char[] xc = s.ToCharArray(); 
    Array.Reverse(xc); 
    return new string(xc); 
} 

在这种情况下,调用的代码将是:

s = s.Reverse(); 

为了操纵整数,你可以这样做:

public static int Increment(this int i) 
{ 
    return i++; 
} 

i = i.Increment();