gpt4 book ai didi

c# - 如何在 C# 中使用派生类型覆盖泛型方法

转载 作者:行者123 更新时间:2023-11-30 13:36:19 26 4
gpt4 key购买 nike

我有以下类(class):

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; }
}

这里是我的测试主类:

void Main()
{
var service = new Service();
var paramA = new ParamA();
paramA.Param2 = "Test2";
service.ApplyChanges<ParamA>(paramA);
}

这个实现有什么问题?如何从我的服务类中覆盖的 ApplyChanges 方法访问 parameters.Param2

一般的想法是我有一个 ServiceBase 并且我希望它的派生类能够将不同的参数类型传递给 ApplyChanges 方法。

最佳答案

我在这里做了一个飞跃,但听起来您打算拥有多个“服务”,每个“服务”都有一个关联的参数类型。

方法 上放置一个类型参数,就像您在示例中所做的那样,强制该方法的所有实现都是多态的。 (这个的技术术语是 higher-rank quantification 。)

相反,您应该将类​​型参数与服务本身相关联。这允许给定的合约实现声明它关联的参数类型。当您使用它时,我不会为基类或类型界限操心。

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# - 如何在 C# 中使用派生类型覆盖泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com