c# 通過反射 實例化類


1. 用Type

   在 website 下

C#代碼  
//定義參數類型數組  
Type[] tps = new Type[2];  
tps[0] = typeof(int);  
tps[1] = typeof(string);  
  
//定義參數數組  
object[] obj = new object[2];  
obj[0] = (object)100;  
obj[1] = (object)"Param Example";  
  
string UserDaoPath = System.Configuration.ConfigurationSettings.AppSettings["UserDao"];  
UserDao userDao = (UserDao)Type.GetType(UserDaoPath).  
            GetConstructor(tps).Invoke(obj );  

2. 用Assembly
在 website 下 這個是導入一個 程序集 然后在程序集里再 實例化類, 我這里其實就是實例化一個類。

C#代碼  
string UserServicePath = System.Configuration.ConfigurationSettings  
                                        .AppSettings["UserService"];  
UserService userService = (IUserService)Assembly.Load(UserServicePath).  
            CreateInstance("UserService");  
 
C#代碼  
<appSettings >  
    <add key="UserService" value="App_Code.Service.UserService"></add>  
</appSettings>  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM