我对泛型有疑问。我写了一个通用类。我从这个类派生出其他类。
最后我想在另一个类中使用这个派生类,但我还没有找到如何让它工作的工作解决方案。
这是我的简化示例:
// Generic base class
public class Information<T>
{
public T StatusCode;
public bool Changed;
}
public class Status1 : Information<Status1.Codes>
{
public enum Codes { None = 0, }
public string AdditionalStatusInformation;
public Status1()
{
StatusCode = Codes.None;
}
}
public class Status2 : Information<Status2.Codes>
{
public enum Codes { OK = 0, }
public Status2()
{
StatusCode = Codes.OK;
}
}
到目前为止一切都很好。我正在使用 Json 发送和读取此信息,这种方法适用于接收器和发送器。适用于 Status1 和 Status2 类。
最后,我有了通用的 ErrorReporter 类,我想在其中使用我的 Status1 或 Status2 类。看来这是不可能的。
public class ErrorReporter<T> where T : Information<T>
{
public readonly T Info = Activator.CreateInstance<T>();
public void Update()
{
if (Info.Changed)
{
Console.WriteLine(Info.StatusCode.ToString());
Console.WriteLine(JsonConvert.SerializeObject(Info));
}
}
}
似乎没有办法正确实例化这个类。
我试过这些
new ErrorReporter<Status1>()
new ErrorReporter<Status1.Codes>()
new ErrorReporter<Information<Status1.Codes>()
我得到了
The type 'TestApp.Program.Status1' cannot be used as type parameter 'T' in
the generic type or method 'TestApp.Program.ErrorReporter<T>'.
There is no implicit reference conversion from 'TestApp.Program.Status1' to
'TestApp.Program.Information<TestApp.Program.Status1>'.
或类似的错误信息。
我可能应该将我的 ErrorReporter 类移动到信息类。
但是从我的 ErrorReporter 类实例化新对象的正确方法是什么?有可能吗?
最佳答案
您需要 T
从 Information<T>
派生,这不是您想要的。
我猜你需要这个,你需要为泛型提供类型参数:
public class ErrorReporter<T, S> where T : Information<S>
{ }
再多一点,您就可以删除反射调用:
public class ErrorReporter<T, S> where T : Information<S>, new()
{
public readonly T Info = new T();
}
关于c# - 使用来自非泛型类的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39658386/