C# - 覆盖带有 ClassName 的方法签名?

发布于 2024-09-12 15:42:42 字数 795 浏览 7 评论 0原文

有没有办法重写抽象类的方法签名,该方法签名使用带有 ClassName 的 ,以便我可以通过引用传递对象而无需重新转换它?

例如,我有一堆对象管理器。我希望它们都包含一个 .Save(Object) 方法,该方法将根据对象状态(插入、更新、删除等)执行适当的保存操作。

我试图创建一个包含这些方法的基类:

protected virtual bool Update<T>(ref T _object) where T : ObjectBase
{
    throw new NotImplementedException();
}

public virtual bool Save<T>(ref T _object) where T : ObjectBase
{ 
    // Figure out which action to take based on _object's state and execute it
}

我希望我的继承类使用如下方式定义方法:

public override bool Update<Consumer>(ref Consumer _object)
{
    return _service.UpdateConsumer(ref _object);
}

我的问题是我无法指定 将现在是 ,并且通过将其保持在 我无法通过 ref 传递它

Is there a way to override an abstract class's method signature which uses <T> with a ClassName so I can pass an object by reference without recasting it?

For example, I have a bunch of Object Managers. I want them all to contain a .Save(Object) method which will perform the appropriate save action based on the object state (Insert, Update, Delete, etc).

I was trying to create a base class which contains these methods:

protected virtual bool Update<T>(ref T _object) where T : ObjectBase
{
    throw new NotImplementedException();
}

public virtual bool Save<T>(ref T _object) where T : ObjectBase
{ 
    // Figure out which action to take based on _object's state and execute it
}

And I wanted my inherited classes to define the methods using something like this:

public override bool Update<Consumer>(ref Consumer _object)
{
    return _service.UpdateConsumer(ref _object);
}

My problem is that I can't specify that <T> will now be <Consumer>, and by keeping it at <T> I can't pass it by ref

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对不⑦ 2024-09-19 15:42:42

您应该使整个基类通用,而不是使方法本身通用。

例如:

public abstract class ObjectManager<T> where T : ObjectBase {
    protected abstract bool Update(T obj);
}

每个具体的 ObjectManager 都应该继承它所管理的类型的 ObjectManager,如下所示:

public class ConsumerManager : ObjectManager<Consumer> {
    protected override bool Update(Consumer obj) {
        ...
    }
}

请注意,顺便说一句,您的参数几乎绝对不应该传递 ref
如果您想更改调用者的变量以引用不同的实例,则只需ref关键字。
有关详细信息,请参阅此处

Instead of making the methods themselves generic, you should make the entire base class generic.

For example:

public abstract class ObjectManager<T> where T : ObjectBase {
    protected abstract bool Update(T obj);
}

Each concrete ObjectManager should inherit ObjectManager of the type that it manages, like this:

public class ConsumerManager : ObjectManager<Consumer> {
    protected override bool Update(Consumer obj) {
        ...
    }
}

Note, by the way, that your parameters should almost definitely not be passed ref.
You only need to ref keyword if you want to change the caller's variable to refer to a different instance.
For more information, see here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文