程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#反射概念以及實例詳解(1)

C#反射概念以及實例詳解(1)

編輯:關於C語言

C#反射的入門學習首先要明白C#反射提供了封裝程序集、模塊和類型的對象等等。那麼這樣可以使用反射動態創建類型的實例,將類型綁定到現有對象,或從現有對象獲取類型並調用其方法或訪問其字段和屬性。如果代碼中使用了屬性,可以利用反射對它們進行訪問。

一個最簡單的C#反射實例,首先編寫類庫如下:

using System;

namespace ReflectionTest
{
public class WriteTest
{
//public method with parametors
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}

//static method with only one parametor
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}

//static method with no parametor
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
}

使用命令行編譯csc /t:library ReflectTest.cs命令進行編譯,生成ReflectTest.dll庫文件。

然後進行下列程序的編寫:

using System;
using System.Reflection;

class TestApp
{
public static void Main()
{
Assembly ass;
Type type;
Object obj;

//Used to test the static method
Object any = new Object();

//Load the dll
//Must indicates the whole path of dll
ass = Assembly.LoadFile(@"D:\Source Code\00.C#
Sudy\01.Reflection\01\ReflectTest.dll");
//Must be Namespace with class name
type = ass.GetType("ReflectionTest.WriteTest");

/**//*example1---------*/

MethodInfo method = type.GetMethod("WriteString");

string test = "test";
int i = 1;

Object[] parametors = new Object[]{test,i};

//Since the WriteTest Class is not Static you should Create the instance of this class
obj = ass.CreateInstance("ReflectionTest.WriteTest");

method.Invoke(
obj,//Instance object of the class need to be reflect
parametors);//Parametors of indicated method

//method.Invoke(any, parametors);//RuntimeError: class reference is wrong

/**//*example2----------*/

method = type.GetMethod("StaticWriteString");

//The first parametor will be ignored
method.Invoke(null, new string[] { "test"});
method.Invoke(obj, new string[] { "test"});//indicates the instance will equals above line
method.Invoke(any, new string[] { "test"});//Even the class reference is wrong

/**//*example3-----------*/

method = type.GetMethod("NoneParaWriteString");

//Sine the method NoneParaWriteString()

has no parametors so do not indicate any parametors
method.Invoke(null, null);

}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved