C # Extracting a class in a static method

Example:

namespace MyProgram.Testing { public class Test1 { public void TestMethod() { String actualType = this.GetType().FullName.ToString(); return; } public static String GetInheritedClassName() { return System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName; } } public class Test2 : Test1 { } public class Test3 { String test2ClassName = Test2.GetInheritedClassName(); } } 

In any case, I want it to return "MyProgram.Testing.Test2", but instead Test2.GetInheritedClassName () returns "MyProgram.Testing.Test1". What do I need to include in this static class to return it (if possible)?

+6
source share
2 answers

The code that prints the type is a base class method. With the exception of the rare Reflection scripts that you indicated above, the execution will not depend on whether the method is called using the derived type or the base type, so the system does not make any differences.

However, you can get around this by specifying a common base type:

  class ClassNameTesterBase <T> where T: ClassNameTester <T>
     {
         public static String getName () {return (typeof (T)). Name;  }
     }

and then defining other types of interests:

  class ClassNameTester1 <T & gt: ClassNameTesterBase <T> ...
     class ClassNameTester2 <T & gt: ClassNameTester1 <T> ...

Then you can optionally define sheet classes:

  class ClassNameTester1: ClassNameTester1 <ClassNameTester1> {}
     class ClassNameTester2: ClassNameTester2 <ClassNameTester2> {}

One small caveat here is that ClassNameTester2 derives its internals from ClassNameTester1 <T> but cannot be replaced with anything related to ClassNameTester1 <ClassNameTester1> ;; if it is used as a static class, this should not be a problem.

+1
source

It's impossible. When you call Test2.GetInheritedClassName , it is actually Test1.GetInheritedClassName , which is called because Test2.GetInheritedClassName does not actually exist (for example, some tools like Resharper will show a warning: access to the static member of the type through a derived type )

Static members do not participate in inheritance, which is logical, since inheritance only makes sense when you are dealing with instances ...

+6
source

Source: https://habr.com/ru/post/893278/


All Articles