【发布时间】:2008-09-16 06:37:37
【问题描述】:
在 C# 方法中是否有有用的 this 赋值示例?我在工作面试中被问过一次,我仍然有兴趣自己回答。
【问题讨论】:
标签: c# language-features
在 C# 方法中是否有有用的 this 赋值示例?我在工作面试中被问过一次,我仍然有兴趣自己回答。
【问题讨论】:
标签: c# language-features
当他们说您不能分配给“this”时,其他答案不正确。没错,你不能为类类型,但你可以为结构类型:
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
在任何时候,结构都可以通过分配给“this”来改变自己。
【讨论】:
使用 this 关键字可确保仅访问当前类型范围内的变量和方法。当字段/属性与局部变量或方法参数之间存在命名冲突时,可以使用此选项。
通常用于构造函数:
private readonly IProvider provider;
public MyClass(IProvider provider)
{
this.provider = provider;
}
在本例中,我们将参数提供者分配给私有字段提供者。
【讨论】:
this的例子。
从语法的角度来看,唯一正确的地方是 C# 3.0 中的扩展方法,当您将方法的第一个参数指定为 foo(ftype this, ...) 时。然后可以将此扩展名用于任何 ftype 实例。但 is 只是语法而不是真正的 ovveride 操作。
【讨论】:
this,并且没有其他语法。
如果你被要求为 this 分配一些东西,这里有很多例子。想到的一个是告诉控制他的爸爸是谁:
class frmMain
{
void InitializeComponents()
{
btnOK = new Button();
btnOK.Parent = this;
}
}
【讨论】:
this的例子。
我知道这个问题早已得到解答,讨论已停止,但这是我在互联网上的任何地方都没有看到的案例,我认为在这里分享可能会有用。
我用它来保持成员的不变性,同时仍然支持序列化。考虑一个像这样定义的struct:
public struct SampleStruct : IXmlSerializable
{
private readonly int _data;
public int Data { get { return _data; } }
public SampleStruct(int data)
{
_data = data;
}
#region IXmlSerializableMembers
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
this = new SampleStruct(int.Parse(reader.ReadString()));
}
public void WriteXml(XmlWriter writer
{
writer.WriteString(data.ToString());
}
#endregion
}
由于我们被允许覆盖this,我们可以在单个实例中保持_data 的不变性。这有一个额外的好处,当反序列化新值时,你可以保证一个新的实例,这有时是一个很好的保证!
}
【讨论】:
您不能覆盖“this”。它指向当前的对象实例。
【讨论】: