如何在类的方法内部访问调用该方法的类实例对象?
在类方法内部访问调用实例的解决方案(C#)
嘿,你问的“如何在类的方法内部访问调用该方法的类实例对象”这个问题,在C#里有个非常直接的解决办法——使用**this关键字**!
什么是this?
this在C#的非静态方法中,直接指代调用当前方法的那个类实例对象。你可以通过它访问实例的属性、字段,甚至调用其他实例方法。
结合你的代码示例修改
下面是基于你给出的Container类,补全并修改GenerateXMLElement方法后的完整示例,展示如何用this访问实例属性:
using System; using System.Xml; public class XmlElementGenerator { // 父类基础框架,可按需扩展 } public class Container : XmlElementGenerator { public string projectcode { get; set; } public string projectname { get; set; } public string projectleader { get; set; } public string barcode { get; set; } public string sampleartid { get; set; } public string sampledescription { get; set; } public string remark { get; set; } public DateTime samplingdate { get; set; } public int samplenumber { get; set; } public XmlElement GenerateXMLElement(XmlDocument xmlDocument) { // 用this直接访问当前实例的所有属性 XmlElement containerElement = xmlDocument.CreateElement("Container"); // 把实例属性绑定到XML元素的属性或子节点 containerElement.SetAttribute("ProjectCode", this.projectcode); containerElement.SetAttribute("ProjectName", this.projectname); containerElement.SetAttribute("Barcode", this.barcode); XmlElement samplingDateNode = xmlDocument.CreateElement("SamplingDate"); samplingDateNode.InnerText = this.samplingdate.ToString("yyyy-MM-dd HH:mm:ss"); containerElement.AppendChild(samplingDateNode); XmlElement sampleCountNode = xmlDocument.CreateElement("SampleNumber"); sampleCountNode.InnerText = this.samplenumber.ToString(); containerElement.AppendChild(sampleCountNode); // 其他属性可按相同逻辑处理 return containerElement; } }
额外说明
- 大多数场景下
this可以省略(比如直接写projectcode和this.projectcode效果一致),但当方法参数名和实例属性名重名时,必须用this区分:public void UpdateSampleNumber(int samplenumber) { // 这里必须用this.samplenumber指代实例属性,否则会把参数赋值给自己 this.samplenumber = samplenumber; } - 注意:
this只能在非静态方法中使用,静态方法属于类本身而非某个实例,因此无法通过this访问实例成员。
内容的提问来源于stack exchange,提问作者Ashen One
相关产品推荐
相关产品推荐

