Is it possible to make a call to static
method from generic function?
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.
You can't do that with constraints, but you can use 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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.