【问题标题】:Create an object with method using c# reflection使用 c# 反射的方法创建对象
【发布时间】:2023-03-19 09:29:01
【问题描述】:

我有一个问题,我需要在 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 方法创建此版本控制服务器对象?

任何帮助将不胜感激。

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    你可以这样调用方法:

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

    请注意,您不应使用 tpcclass.GetMethods()[32]; 之类的东西,因为反射不能保证您返回方法的顺序。更好用GetMethod([methodname]);

    【讨论】:

    • 谢谢!使用 GetMethod([方法名]);我的问题是有多个同名方法,这就是为什么我尝试使用 getmethods 访问它的原因。但这并不总是以相同的顺序是非常可怕的。有没有办法解决这个问题?
    • @JamesWard 你应该接受这个重载:msdn.microsoft.com/en-us/library/6hy0h0z1%28v=vs.110%29.aspx。如果失败,请使用 GetMethods 并使用 linqs Single 方法指定您搜索的方法。
    • 非常有帮助,正是我需要的。
    【解决方案2】:

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

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

    【讨论】:

    • 哦,非常有用!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2012-05-15
    • 2016-11-14
    • 2022-11-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    相关资源
    最近更新 更多