开发者

extension methods as static class methods [duplicate]

This question already has answers here: 开发者_运维知识库 Closed 12 years ago.

Possible Duplicate:

Can you add extension methods that you call like static methods?

I would like to add NewSequentialGuid function on the Guid system type, so I can use like following:

Id = Guid.NewSequentialGuid()

namespace MyExtensions
{
    public static class GuidExtensions
    {
        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out Guid guid);

        public static Guid NewSequentialGuid(this Guid guid)
        {
            const int RPC_S_OK = 0;
            Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException
                  ("UuidCreateSequential failed: " + hr);
            return g;
        }
    }
}

But I cannot get this to work, it only works with instance variables, any idea how to add this to extended class as a static method?


You can't.

They were created to look like instance methods and can't be make to work as class (static) methods.

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.

And:

Extension methods are defined as static methods but are called by using instance method syntax.


Can you add extension methods that you call like static methods?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜