我已經創建了一個靜態類,並在反射中使用它。 但是,當我訪問的類,它的顯示5種方法的方法,但我只有1 創造了額外的方法是C#中靜態類的反射#
Write
ToString
Equals
GetHashCode
GetType
但我只創造了書寫方法。
一個靜態方法可以在靜態類中,但這些額外的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();
}
}
}
但如何建立一個靜態的類的對象來訪問這些方法 靜態類不能有非靜態方法
但我無法從我的類中獲取這些方法,就像我們獲得的靜態類'ReflectionTest.GetType()' – 2012-03-09 11:35:24
而且我們也無法爲靜態類創建對象。以及如何不靜態成員可以繼承靜態類 – 2012-03-09 11:36:25
正確的,那是因爲這些方法不是靜態的。但是,您正在探索Type對象,並且您會看到靜態方法和非靜態方法。 – Andrei 2012-03-09 11:39:41