开发者

How do I add .Net C# class extension of System.Array

I am quite familiar with class extensions, but wasn't expecting the following behavior.

I expected the following to extend System.Array, but it didn't. Instead, it exten开发者_Go百科ded instances of System.Array. Why?

public static T[] Concatenate<T>(this Array value1, Array value2)
{
    int l1 = value1 == null ? 0 : value1.Length;
    int l2 = value2 == null ? 0 : value2.Length;

    T[] result = new T[l1 + l2];

    if (l1 > 0)
    {
        Array.Copy(value1, 0, result, 0, l1);
    }

    if (l2 > 0)
    {
        Array.Copy(value2, 0, result, l1, l2);
    }

    return result;
}

...

Array. // no Concatenate

string[] s = new string[1];
s.Concatenate<string>... // appears here


Because you can only define extension methods for instances of types. To invoke them you either use the instance-method invocation like syntax

var result = s.Concatenate(t);

or the standard static-method invocation syntax

var result = ArrayExtensions.Concatenate(s, t);

Again, you can not add methods to Array, only to instances of Array (and really, you aren't adding methods, it's just a compiler trick that makes it look like you did).

By the way, I would just write your method as

return value1.Concat(value2).ToArray();


I expected the following to extend System.Array, but it didn't. Instead, it extended instances of System.Array. Why?

Because there is no way to define static extensions method - only instance extension method can be defined (From MSDN:):

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

However, you can call your extension method in static manner, but using your class extension name:

MyExtensions.Concatenate(s, f);

It's very Pythonic way to define methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜