C#泛型-推断静态工厂成员的类型 [英] C# Generics - Infer Type of static factory members
问题描述
我想调用使用泛型的类的静态成员,而不指定类型并让编译器推断它们.
I would like to invoke static members of a class that uses generics without specifying the type and having the compiler infer them.
例如,这是我要与Static Factory成员一起使用的通用类:
For example this is the generic class I want to use, with the Static Factory member:
public class GenericClass<T>
{
public T Member;
// Constructor
public GenericClass(T value)
{
Member = value;
}
// static factory method
public static GenericClass<T> StaticFactory(T resultData)
{
return new GenericClass<T>(resultData);
}
}
如果我尝试以下操作,则不会编译:
If I try the following does not compile:
public class Class1
{
public GenericClass<string> returnResult1()
{
return GenericClass.StaticFactory("Won't Compile, but it's clear that T is a string");
}
public GenericClass returnResult2()
{
return GenericClass.StaticFactory("Won't Compile, but it's clear that T is a string");
}
}
错误1使用通用类型'SampleStatic.GenericClass'需要1个类型参数
Error 1 Using the generic type 'SampleStatic.GenericClass' requires 1 type arguments
为什么静态成员不能喜欢以下内容?
Why can't I do like the following with static members?
public void ICanInferTheType<T1>(T1 item);
public void returnResult4()
{
ICanInferTheType("Compiles, recognizes type string");
}
谢谢-
推荐答案
好,感谢@recursive!这个答案几乎是完美的,它需要在方法名称中再输入一个,例如:
Ok, thanks to @recursive! That answer is almost perfect, it requires one more in the name of the method, like this:
public static class GenericClass
{
// static factory method
public static GenericClass<T> StaticFactory<T>(T resultData)
{
return new GenericClass<T>(resultData);
}
}
这篇关于C#泛型-推断静态工厂成员的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!