C#中静态类的反射

Kis*_*mar 7 .net c# reflection static

我创建了一个静态类并在Reflection中使用它.但是当我访问该类的方法时,它显示了5个方法但我只创建了1个.额外的方法是

Write
ToString
Equals
GetHashCode
GetType
Run Code Online (Sandbox Code Playgroud)

但我只创建了Write方法.

一个静态方法可以在静态类中,但这些额外的4种方法不是静态方法,而是从它们驱动的位置开始.什么是基类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace ReflectionDemo
{
    static class ReflectionTest
    {
        public static int Height;
        public static int Width;
        public static int Weight;
        public static string Name;

        public static void Write()
        {
            Type type = typeof(ReflectionTest);         //Get type pointer
            FieldInfo[] fields = type.GetFields();      //obtain all fields
            MethodInfo[] methods = type.GetMethods();
            Console.WriteLine(type);
            foreach (var item in methods)
            {
                string name = item.Name;
                Console.WriteLine(name);
            }

            foreach (var field in fields)
            {
                string name = field.Name; //(null); //Get value
                object temp = field.GetValue(name);
                if (temp is int) //see if it is an integer
                {
                    int value = (int)temp;
                    Console.Write(name);
                    Console.Write("(int) = ");
                    Console.WriteLine(value);
                }
                else if (temp is string)
                {
                    string value = temp as string;
                    Console.Write(name);
                    Console.Write("(string) = ");
                    Console.WriteLine(value);
                }
            }
        }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            ReflectionTest.Height = 100;
            ReflectionTest.Width = 50;
            ReflectionTest.Weight = 300;
            ReflectionTest.Name = "Perl";

            ReflectionTest.Write();

            Console.ReadLine();            
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如何创建静态类的对象来访问那些方法静态类不能有非静态方法

Jon*_*eet 24

只能在静态类中声明静态成员- 但就CLR而言,它只是另一个类,它恰好只有静态成员,没有构造函数,并且都是抽象和密封的.CLR没有静态类的概念 ......因此该类仍然继承了实例成员object.

这是区分语言功能,框架功能和运行时功能的重要原因.


And*_*rei 10

C#中的每个类型都从(直接或间接)继承 System.Object.因此继承Object的方法ToString,GetHashCode,EqualsGetType.这就是为什么你在探索ReflectionTest类型对象的所有方法时看到它们的原因.要仅获取静态方法,请使用此BindingFlags枚举成员:

type.GetMethods(System.Reflection.BindingFlags.Static)
Run Code Online (Sandbox Code Playgroud)