[英]Static method call from generic function
Is it possible to make a call to static
method from generic function? 是否可以从泛型函数调用
static
方法?
I need to do something like this: 我需要做这样的事情:
public static T CreateNewProject<T, V>(string token, string projectName)
where V : IProject<T>
{
V.LoadProject();
}
where LoadProject()
MUST be some static
method of some class. 其中
LoadProject()
必须是某个类的某些static
方法。
You can't do that with constraints, but you can use Reflection
. 您不能使用约束来做到这一点,但是可以使用
Reflection
。 It looks like the only choice in this case: 在这种情况下,它似乎是唯一的选择:
typeof(V).GetMethod("LoadProject", BindingFlags.Static | BindingFlags.Public)
.Invoke(null);
What you could do is instead of using static classes is use a singleton: 您可以使用单例来代替静态类:
public interface ICanLoadProject
{
void LoadProject(string token, string projectName);
}
Implementation: 实现方式:
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*/ }
}
then the generic works with: 然后通用可以使用:
where V : ICanLoadProject
all you have to do with the code accessing the Method before is: 与之前访问该方法的代码有关的所有事情是:
SampleProjectLoader.Instance.LoadProject("token","someName");
the method could be: 该方法可以是:
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
}
}
And will be called like: 并且将被称为:
static void Main(string[] args)
{
object result = SampleProjectLoader.Instance.CreateNewProject<object, SampleProjectLoader>("token", "someName");
}
Or better yet: 或者更好:
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
}
}
and call with: 并致电:
SampleProjectLoader.Instance.CreateNewProject<object>("token", "someName");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.