C#的Python风格的类方法?

AKX*_*AKX 6 c# python class-method

有没有办法classmethod在C#中用Python 做什么?

也就是说,一个静态函数可以根据它使用的子类将Type对象作为(隐式)参数.

我想要的一个例子就是

class Base:
    @classmethod
    def get(cls, id):
        print "Would instantiate a new %r with ID %d."%(cls, id)

class Puppy(Base):
    pass

class Kitten(Base):
    pass

p = Puppy.get(1)
k = Kitten.get(1)
Run Code Online (Sandbox Code Playgroud)

预期的产出是

Would instantiate a new <class __main__.Puppy at 0x403533ec> with ID 1.
Would instantiate a new <class __main__.Kitten at 0x4035341c> with ID 1.
Run Code Online (Sandbox Code Playgroud)

(这里在键盘上的代码相同.)

Jul*_*iet 2

原则上,你可以这样写:

class Base
{
    public static T Get<T>(int id)
        where T : Base, new()
    {
        return new T() { ID = id };
    }

    public int ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以写了var p = Base.Get<Puppy>(10)。或者,如果您感到受虐狂,您可以编写Puppy.Get<Puppy>(10)Kitty.Get<Puppy>;) 在所有情况下,您都必须显式而不是隐式地传递类型。

或者,这也有效:

class Base<T> where T : Base<T>, new()
{
    public static T Get(int id)
    {
        return new T() { ID = id };
    }

    public int ID { get; set; }
}

class Puppy : Base<Puppy>
{
}

class Kitten : Base<Kitten>
{
}
Run Code Online (Sandbox Code Playgroud)

您仍然需要将类型传递回基类,这允许您Puppy.Get(10)按预期编写。

var p = new Puppy(10)但是,在同样简洁、更惯用的情况下,还有理由这样写吗?可能不会。