使用c#reflection创建一个方法对象

时间:2016-01-26 23:02:22

标签: c# reflection

我有一个问题,我需要在c#中加载dll后使用反射创建一个tfs版本控制服务器对象。我在反射中初始化时遇到了麻烦,因为它没有构造函数。如果没有反射,通常使用团队项目集合对象中的getService方法创建对象。这是我的代码:

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方法创建此版本控制服务器对象?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以这样调用方法:

var closedMethod = getService.MakeGenericMethod(VersionControlServerClass);
object vcs = closedMethod.Invoke(tpc, null);

作为一个注释,您不应该使用tpcclass.GetMethods()[32];之类的内容,因为反射并不能保证返回方法的顺序。更好地使用GetMethod([methodname]);

答案 1 :(得分:0)

请注意TfsTeamProjectCollection实现IServiceProvider,它实际上具有非通用版本的GetService:

object vcs = ((IServiceProvider)tpc).GetService(VersionControlServerClass);