In python, an instance method self
points to the class instance, just like this
in C#.
In python, a class method self
points to the class. Is there a C# equivalent?
这一点是有益的,例如:
例子:
class A:
values = [1,2]
@classmethod
def Foo(self):
print "Foo called in class: ", self, self.values
@staticmethod
def Bar():
print "Same for all classes - there is no self"
class B(A):
# other code specific to class B
values = [1,2,3]
pass
class C(A):
# other code specific to class C
values = [1,2,3,4,5]
pass
A.Foo()
A.Bar()
B.Foo()
B.Bar()
C.Foo()
C.Bar()
成果:
Foo called in class: __main__.A [1, 2]
Same for all classes - there is no self
Foo called in class: __main__.B [1, 2, 3]
Same for all classes - there is no self
Foo called in class: __main__.C [1, 2, 3, 4, 5]
Same for all classes - there is no self
这可以成为一种伟大的工具,使在班级情况下(无一例)的普通法典能够提供由子级界定的定制行为(无需次等)。
在我看来,C#静态方法正好像是伪装方法,因为没有哪类人实际使用这种方法。
But is there a way to do class methods in C#?? Or at least determine which class invoked a method, for example:
public class A
{
public static List<int> values;
public static Foo()
{
Console.WriteLine("How can I figure out which class called this method?");
}
}
public class B : A
{
}
public class C : A
{
}
public class Program
{
public static void Main()
{
A.Foo();
B.Foo();
C.Foo();
}
}