扩展方法作为静态类方法

发布于 2024-10-08 22:09:45 字数 954 浏览 3 评论 0原文

可能的重复:
您可以添加像静态一样调用的扩展方法吗方法?

我想在 Guid 系统类型上添加 NewSequentialGuid 函数,这样我就可以使用如下内容:

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;
        }
    }
}

但我不能让它工作,它只适用于实例变量,知道如何将其作为静态方法添加到扩展类中吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不必你懂 2024-10-15 22:09:45

你不能。

它们被创建为看起来像实例方法,并且不能用作类(静态)方法。

来自 MSDN

扩展方法是一种特殊的静态方法,但它们的调用方式就像扩展类型上的实例方法一样。

和:

扩展方法被定义为静态方法,但使用实例方法语法进行调用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文