从泛型函数调用静态方法

时间:2015-02-24 11:16:18

标签: c# .net oop generics static

是否可以从泛型函数调用static方法?

我需要做这样的事情:

public static T CreateNewProject<T, V>(string token, string projectName)
     where V : IProject<T>
{
   V.LoadProject();
}

其中LoadProject()必须是某个类的static方法。

2 个答案:

答案 0 :(得分:3)

您无法使用约束来执行此操作,但您可以使用Reflection。在这种情况下,它看起来是唯一的选择:

typeof(V).GetMethod("LoadProject", BindingFlags.Static | BindingFlags.Public)
         .Invoke(null);

答案 1 :(得分:2)

你可以做的不是使用静态类而是使用单例:

public interface ICanLoadProject
{
    void LoadProject(string token, string projectName);
}

实现:

public class SampleProjectLoader : ICanLoadProject
{
    private static SampleProjectLoader instance = new SampleProjectLoader();

    private SampleProjectLoader(){} 

    public static SampleProjectLoader Instance { get{ return instance; } }

    public void LoadProject(string token, string projectName)
    { /*Your implementation*/ }

}

然后通用工具:

where V : ICanLoadProject

以前访问Method的代码所需要做的就是:

SampleProjectLoader.Instance.LoadProject("token","someName");

方法可以是:

public static class ExtensionMethods
{
    public static T CreateNewProject<T, V>(this V loader, string token, string projectName) where V : ICanLoadProject
    {
        loader.LoadProject(token, projectName);
        return default(T); //no clue what you want to return here
    }
}

将被称为:

static void Main(string[] args)
{
    object result = SampleProjectLoader.Instance.CreateNewProject<object, SampleProjectLoader>("token", "someName");
}

或者更好:

public static class ExtensionMethods
{
    public static T CreateNewProject<T>(this ICanLoadProject loader, string token, string projectName)
    {
        loader.LoadProject(token, projectName);
        return default(T); //no clue what you want to return here
    }
}

并致电:

SampleProjectLoader.Instance.CreateNewProject<object>("token", "someName");