C# - 覆盖带有 ClassName 的方法签名?
有没有办法重写抽象类的方法签名,该方法签名使用带有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使整个基类通用,而不是使方法本身通用。
例如:
每个具体的 ObjectManager 都应该继承它所管理的类型的
ObjectManager
,如下所示:请注意,顺便说一句,您的参数几乎绝对不应该传递
ref
。如果您想更改调用者的变量以引用不同的实例,则只需
ref
关键字。有关详细信息,请参阅此处。
Instead of making the methods themselves generic, you should make the entire base class generic.
For example:
Each concrete ObjectManager should inherit
ObjectManager
of the type that it manages, like this: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.