C# 反射

來源:互聯網
上載者:User

class Program
{
static void Main(string[] args)
{
//Console.WriteLine(Untity.Rollover(Console.ReadLine()));
//Console.WriteLine(Untity.make('w', 5));
//foreach (string s in Untity.GetStringArray(Console.ReadLine()))
//{
// Console.WriteLine(s);
//}
Assembly ass = Assembly.LoadFile(@"E:\360data\重要資料\我的文件\visual studio 2010\Projects\dll\lrbrary\bin\Debug\lrbrary.dll");//載入程式集

Type type = ass.GetType("lrbrary.Untity");//命名空間.類 。執行個體化 命名空間和類的名字必須一起指定
FieldInfo[] fields = type.GetFields();//擷取欄位
PropertyInfo[] propertys = type.GetProperties();//擷取屬性
MethodInfo[] methods = type.GetMethods();//擷取方法
foreach (MethodInfo method in methods)
{
Console.WriteLine("方法名稱:" + method.Name);
Console.WriteLine("參數個數:" + method.GetParameters().Length);
foreach (ParameterInfo param in method.GetParameters())
{
Console.WriteLine(param.ParameterType + ":" + param.Name);
}
}
object obj = ass.CreateInstance("lrbrary.untity", true);
MethodInfo meth = methods[2];//調用方法
Console.WriteLine(meth.Invoke(obj, new object[] { }));//我們想用的方法是一個靜態方法,這時候Invoke的時候,對於第一個參數是無視的,也就是我們寫什麼都不會被調用,即使我們隨便new了一個any這樣的Object,當然這種寫法是不推薦的。但是我們如果Invoke的時候用了類型不一致的執行個體來做為參數的話,將會導致一個運行時的錯誤。
//Console.WriteLine(meth.Invoke(null, null));//調用無參數靜態方法的例子,這時候兩個參數我們都不需要指定,用null就可以了。
Console.ReadKey();
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.