说我有以下两个类,理想情况下做我想要的:
Foo.cs:
public class Foo
{
private int Type { get; set; } = 0;
public FooHelper FooHelper
{
get
{
switch (Type)
{
case 1:
return new FooHelper<Guid>("Foo", "Bar", "foobar", "", Guid.NewGuid());
case 2:
default:
return new FooHelper<int>("Bar", "Foo", "", "", 11);
}
}
}
public Foo(int type)
{
Type = type;
}
}
Run Code Online (Sandbox Code Playgroud)
FooHelper.cs:
public class FooHelper<T> where T : struct
{
public string Controller { get; set; } = string.Empty;
public string Action { get; set; } = string.Empty;
public string Area { get; set; } = string.Empty;
public string NameParameter { get; set; } = string.Empty;
public T IdParameter { get; set; } = default(T);
public FooHelper() { }
public FooHelper(string controller, string action, string area, string name, T id)
{
Controller = controller;
Action = action;
Area = area;
NameParameter = name;
IdParameter = id;
}
}
Run Code Online (Sandbox Code Playgroud)
根据作为非泛型类Foo的构造函数的参数传入的整数值,属性FooHelper基于Guid或int 返回泛型类FooHelper的新实例.
但是,如果不让Foo也通用,我似乎无法做到这一点,我不想要.我得到的错误是在FooHelper的属性行上,说明:
Using the generic type 'FooHelper<T>' requires 1 type arguments
这是有道理的,但在那一点我不知道.我想确定Foo构造函数中FooHelper的类型.
我错过了什么,或者在这种情况下是不是可以做我想做的事情?
问题是公共FooHelper FooHelper甚至不会编译,因为没有调用类型FooHelper.但是也有FooHelper<int>和FooHelper<Guid>这不过鸵鸟政策有什么共同点.因此,这个问题(再次)是由于您在运行时提供信息(类型转换)并期望编译器在编译时推断出正确的泛型类型,这是不可能的.
你可以做的是创建一个非泛型的接口,从你的所有助手派生出来,你的方法返回:
public interface IFooHelper { ... }
public class FooHelper<T> : IFooHelper where T : struct { ... }
Run Code Online (Sandbox Code Playgroud)
现在在你的Foo类中:
public IFooHelper FooHelper
{
get
{
switch (Type)
{
case 1:
return new FooHelper<Guid>("Foo", "Bar", "foobar", "", Guid.NewGuid());
case 2:
default:
return new FooHelper<int>("Bar", "Foo", "", "", 11);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如上所述,在编译时,无法知道实际的泛型类型参数究竟是什么,因为该类型甚至不存在.