今天小編給大家分享一下C#如何使用反射機制實現延遲綁定的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
● 創建類型的實例
● 觸發方法
● 獲取屬性、字段信息
● 延遲綁定
......
1、Type類的靜態方法
Type type = Type.GetType("somenamespace.someclass");
2、通過typeof
Type type = typeof(someclass);
Type type = asm.GetType("somenamespace.someclass");
有這樣的一個類:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public float Score { get; set; }
public Student()
{
this.Id = -1;
this.Name = string.Empty;
this.Score = 0;
}
public Student(int id, string name, float score)
{
this.Id = id;
this.Name = name;
this.Score = score;
}
public string DisplayName(string name)
{
return string.Format("學生姓名:{0}", name);
}
public void ShowScore()
{
Console.WriteLine("學生分數是:" + this.Score);
}
}通過如下獲取反射信息:
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication1.Student");
//Type type = typeof (Student);
Console.WriteLine(type.FullName);
Console.WriteLine(type.Namespace);
Console.WriteLine(type.Name);
//獲取屬性
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
Console.WriteLine(prop.Name);
}
//獲取方法
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine(method.ReturnType.Name);
Console.WriteLine(method.Name);
}
Console.ReadKey();
}在通常情況下,為對象實例賦值是發生在編譯期,如下:
Student stu = new Student(); stu.Name = "somename";
而"延遲綁定",為對象實例賦值或調用其方法是發生在運行時,需要獲取在運行時的程序集、Type類型、方法、屬性等。
//獲取運行時的程序集
Assembly asm = Assembly.GetExecutingAssembly();
//獲取運行時的Type類型
Type type = asm.GetType("ConsoleApplication1.Student");
//獲取運行時的對象實例
object stu = Activator.CreateInstance(type);
//獲取運行時指定方法
MethodInfo method = type.GetMethod("DisplayName");
object[] parameters = new object[1];
parameters[0] = "Darren";
//觸發運行時的方法
string result = (string)method.Invoke(stu, parameters);
Console.WriteLine(result);
Console.ReadKey();以上就是“C#如何使用反射機制實現延遲綁定”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。