是否可以覆盖分配"="?在C#中 [英] Is it possible to override assignment "=" in C#
问题描述
我有一个复杂的对象类型,为此我将覆盖"base.ToString()"方法,以便它返回字符串属性值.
I have a complex object type for which I'm overriding the "base.ToString()" method so that it returns a string property value.
例如:
class foo
{
public string StringValue{get;set;}
public int SomeOtherValue{ get;set;}
public override ToString()
{
return StringValue;
}
}
因此,这使我可以轻松地检索StringValue属性的值.
So this allows me to use retrieve the value of the StringValue property easily.
有没有一种方法可以覆盖或扩展基本功能,以便可以使用下面的简单代码来设置 StringValue
属性?
Is there a way in which I can override or extend the base functionality so that I can use simple code such as below to set the StringValue
property?
foo aFoo = new foo();
aFoo = "Some string value";
推荐答案
否,这是不可能的.赋值运算符不是不可替代的,并且有充分的理由.
No, this is not possible. The assignment operator is not overridable and for good reason.
即使在C#和现代的面向对象的编程语言的范围内,开发人员也经常滥用"该系统,使其无法完成其应做的事情.如果您分配的含义不同于将引用值传递给变量的值给赋值运算符的含义,那么请考虑一下没有经验的开发人员使用它会造成的混乱.
Developers are, even within the confines of C# and modern object-oriented programming languages, often "abusing" the system to make it do things it's not supposed to do. If you could assign a different meaning than passing a reference value to a variable to an assignment operator, think of the chaos that would create when inexperienced developers use it.
您可以做的是提供允许对象从字符串中获取其值的方法,如下所示:
What you can do is to provide methods that allow your object to take its values from a string, like so:
afoo.TakeValuesFrom("Some string value");
或
MyThingy afoo = MyThingy.FromString("Some string value");
与您要问的内容几乎相同,并且完全合法且可读.
which would be almost identical to what you are asking, and perfectly legal and readable.
这篇关于是否可以覆盖分配"="?在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!