如何在C#中使用派生类型重写泛型方法 [英] How to override generic method with derived type in c#
问题描述
我有以下课程:
public interface IService
{
void ApplyChanges<T>(T parameters) where T : ParamBase;
}
public class ServiceBase : IService
{
public virtual void ApplyChanges<T>(T parameters) where T : ParamBase
{ }
}
public abstract class Service : ServiceBase
{
public override void ApplyChanges<T>(T parameters) where T : ParamBase
{
Console.WriteLine(parameters.Param2);
//Apply changes logic here...
}
}
public abstract class ParamBase
{
public string Param1 { get; set; }
}
public class ParamA : ParamBase
{
public string Param2 { get; set; }
}
这是我的考试主要班级:
Here my test main class:
void Main()
{
var service = new Service();
var paramA = new ParamA();
paramA.Param2 = "Test2";
service.ApplyChanges<ParamA>(paramA);
}
该实现有什么问题?如何从Service类中重写的 ApplyChanges
方法访问 parameters.Param2
?
What is wrong with that implementation? How can I access parameters.Param2
from the overriden ApplyChanges
method in my Service class?
总体思路是,我有一个ServiceBase,并且希望其派生类能够将不同的参数类型传递给ApplyChanges方法.
The general idea is that I have a ServiceBase and I want to be able for its derived classes to pass different parameter types to the ApplyChanges method.
推荐答案
我在这里取得了飞跃,但这听起来像您打算拥有多个服务",每个服务都具有关联的参数类型.
I'm making a leap here, but it sounds like you intend to have multiple "services", each with an associated parameter type.
将类型参数放在方法上,迫使该方法的所有实现都是多态的.(此技术术语为 高级量化 .)
Putting a type parameter on the method, as you have done in the example, forces all implementations of that method to be polymorphic. (The technical term for this is higher-rank quantification.)
相反,您应该将type参数与服务本身相关联.这允许合同的给定实现声明与之关联的参数类型.当您使用它时,我不会理会基类或类型界限.
Instead, you should associate the type parameter with the service itself. This allows a given implementation of the contract to declare which parameter type it's associated with. While you're at it, I wouldn't bother with the base classes or the type bounds.
interface IService<in T>
{
void ApplyChanges(T param);
}
class Param1
{
public int X { get; set; }
}
class Service1 : IService<Param1>
{
public void ApplyChanges(Param1 param)
{
param.X = 123;
}
}
class Param2
{
public int Y { get; set; }
}
class Service2 : IService<Param2>
{
public void ApplyChanges(Param2 param)
{
param.Y = 456;
}
}
这篇关于如何在C#中使用派生类型重写泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!