C# 模仿覆盖赋值运算符 (=) [英] C# mimic overridding the assignment operator (=)

查看:37
本文介绍了C# 模仿覆盖赋值运算符 (=)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有点简单的包装类有一点问题.

I've got a bit of a problem with a somewhat simple wrapper class I have.

看起来像这样:

public class Wrapper<T>
{
  private T _value;

  public Wrapper<T>(T value)
  {
    _value = value;
  }

  public static implicit operator Wrapper<T>(T value)
  {
    return new Wrapper<T>(value);
  }

  public static implicit operator T(Wrapper<T> value)
  {
    return value._value;
  }
}

我已经覆盖了从和到 T 的隐式转换器,因此它的行为几乎就像 T 本身的一个实例.

I've overriden the implicit converters from and to T, so it behaves almost like an instance of T itself.

例如

Wrapper<int> foo = 42;

但是,在将 Wrapper 的一个实例分配给另一个实例时,我遇到了一个小问题,因为我只想分配第二个 Wrapper 类的值.

However I've got a slight problem when assigning one instance of Wrapper to another, since I only want to assign the value of the second Wrapper class.

所以现在,我必须这样做:

So right now, I have to do this:

Wrapper<int> foo = 42;
Wrapper<int> bar = (int)foo;

或者通过属性公开 _value.

Or expose _value publicly through a property.

然而,由于这是在图书馆中,我不希望用户依赖于记住这一点,你们知道我如何模仿覆盖赋值运算符吗?

However since this is in a library, and I don't want the user to depend on remembering this, do you guys have any idea how I could mimic overridding the assignment operator ?

仅更改指针的问题(就像将类实例分配给另一个实例时一样),是我有一个指向这些 Wrapper 对象的指针字典,所以我不能让它们一直更改,因为字典将停止匹配.

The problem in just changing the pointer (as it does when assigning a class instance to another), is that I've got a dictionary of pointers to these Wrapper objects, so I cannot have them changing all the time, since the dictionary would stop matching then.

我知道这是否有点令人困惑,所以如果我遗漏了任何重要的内容,请随时询问:-)

I can see if this is somewhat confusing, so if I've left anything important out, please feel free to ask :-)

推荐答案

由于赋值运算符不能重载,所以没有真正好的解决方案.正如其他人指出的那样,使用结构体会给你你想要的赋值语义,但随后你会面临值语义——通常不是一件好事.

Since the assignment operator can't be overloaded, there isn't a real good solution. As somebody else pointed out, using a struct will give you the assignment semantics that you want, but then you're faced with value semantics--often not a good thing.

一种选择是重载构造函数:

One option is to overload the constructor:

public Wrapper(Wrapper<T> w)
{
    _value = w._value;
}

这将导致这种语法:

Wrapper<int> foo = 42;
Wrapper<int> bar = new Wrapper<int>(foo);

虽然比你所拥有的更冗长,但它读起来更好.

Although more verbose than what you have, it reads better.

或者你可以添加一个 Clone 方法(不是 ICloneable 接口),这样你就可以写:

Or you could add a Clone method (not the ICloneable interface), so that you could write:

Wrapper<int> bar = foo.Clone();

您可以变得非常有创意并重载某些运算符,使其基本上什么都不做.不过,我不建议这样做.对这类事情使用运算符重载通常会使代码变得晦涩难懂,而且经常会出错.

You could get really creative and overload some operator, making it do essentially nothing. I wouldn't recommend that, though. Using operator overloading for those kinds of things typically makes code cryptic and often breaks.

这篇关于C# 模仿覆盖赋值运算符 (=)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆