extension methods as static class methods [duplicate]
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?
精彩评论