我有一個問題,我需要在c#中加載dll後使用反射創建一個tfs版本控制服務器對象。因爲它沒有構造函數,所以在反射中初始化它時遇到了問題。在沒有反射的情況下,通常使用團隊項目集合對象中的getService方法創建對象。這裏是我的代碼:使用c#反射方法創建一個對象
namespace SendFiletoTFS
{
class Program
{
static void Main(string[] args)
{
String tfsuri = @"uri";
NetworkCredential cred = new NetworkCredential("user", "password", "domain");
// Load in the assemblies Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.VersionControl.Client.dll
Assembly tfsclient = Assembly.LoadFrom(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll");
Assembly versioncontrol = Assembly.LoadFrom(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll");
// Create Team Project Collection
Type tpcclass = tfsclient.GetType(@"Microsoft.TeamFoundation.Client.TfsTeamProjectCollection");
// The 'getService' method.
MethodInfo getService = tpcclass.GetMethods()[32];
object tpc = Activator.CreateInstance(tpcclass, new object[] { new Uri(tfsuri), cred });
Type VersionControlServerClass = versioncontrol.GetType(@"Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer");
// Code I'm trying to emulate in reflection, this is how I would normally do it without reflection.
//VersionControlServer versionControl = tpc.GetService<VersionControlServer>();
// Create VersionControlServer Class. This line will not work and give a no constructor found exception.
object vcs = Activator.CreateInstance(VersionControlServerClass, new object[] { tpc });
//How do I create the vcs object ?
}
}
}
是有一些方法可以讓我創建使用的getService方法在團隊項目集合類此版本控制服務器的對象?
任何幫助將不勝感激。
謝謝!與GetMethod([methodname]);我有問題,有多個同名的方法,這就是爲什麼我試圖用getmethods訪問它。但這並不總是以相同的順序是非常可怕的。有沒有解決的辦法? –
@JamesWard你應該接受這個超載然後:https://msdn.microsoft.com/en-us/library/6hy0h0z1%28v=vs.110%29.aspx。如果失敗,請使用GetMethods並使用linqs Single方法指定要搜索的方法。 – thehennyy
特別有用,正是我所需要的。 –