【问题标题】:C# - use fields and methods without repeating the object name each time [duplicate]C# - 使用字段和方法而不每次都重复对象名称[重复]
【发布时间】:2018-08-31 13:49:19
【问题描述】:

我刚刚开始学习 C#。我遇到的一个常见问题是,当我使用对象实例并想要访问/分配多个字段时,我每次都必须调用对象名称。我来自 Delphi 的背景,我想知道 C# 是否有类似于 with..do 块的东西。

例如。假设我有 School 类,字段为 NameAddress

在 Delphi 中,我可以执行以下操作

mySchool = School.new();
with mySchool do
begin
 Name := 'School Name';
 Address := 'School Address';
end

编译器会理解 NameAddress 正在被 mySchool 对象调用。

而在 C# 中我必须执行以下操作

mySchool = new School();
mySchool.Name = "School Name";
mySchool.Address = "School Address";

我只是想知道是否有一种类似于上述 Delphi 的语言结构可以消除我重复输入对象名称的需要。

我知道在这个例子中是相当微不足道的,我宁愿使用参数化构造函数,但我的问题是,当我用同一个对象做很多事情时,拥有这样的语言结构会为我节省很多打字。

此外,虽然我对命名空间有模糊的了解,但我的理解是您不能将对象/变量用作命名空间。如果我错了,请纠正我。

【问题讨论】:

  • 您创建类,在您指定的构造函数上,括号上传递的参数可能被实例化为属性。我对 c# 不是超级精明,因为我讨厌微软,我只使用 C# 来实现统一,但由于它与 python/java 等非常相似,所以它应该类似于这个类 School(Name, Address){ #unsure if you need调用构造方法或者这就足够了** str Name = this.Name; str 地址 = this.Address; return School #你可能不需要返回类对象 mySchool = new School("Hogwarts", "Somewhere Lane")

标签: c#


【解决方案1】:

在这种情况下,您可以使用object initializer

var mySchool = new School
{
    Name = "School Name",
    Address = "School Address"
};

【讨论】:

  • 这很有帮助,但如果我想简单地连续多次使用该对象。
【解决方案2】:

我认为所选的答案并没有满足您的要求。

通过使用对象初始化器,您仍然必须每次手动输入属性名称。

构造函数就是你要找的东西:

class Program
{
    static void Main(string[] args)
    {
        School school1 = new School("School Name", "School Address");
    }
}

public class School
{
    public string Name { get; set; }
    public string Address { get; set; }

    public School(string name, string address)
    {
        this.Name = name;
        this.Address = address;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多