gpt4 book ai didi

c# - 有方法的属性?

转载 作者:行者123 更新时间:2023-11-30 13:17:22 26 4
gpt4 key购买 nike

也许我忽略了一些明显的东西,但我在代码中看到您可能有一个像“HairColor”这样的属性,然后是一个像“HairColor.Update()”这样的方法。这可能吗?

Person person = new Person(int personID);
person.HairColor = "Blonde";
person.HairColor.Update();

我希望能够根据具体情况扩展特定属性。我想我可以有一个名为“HairColorUpdate”的方法,但似乎 HairColor.Update() 应该是可能的。我不想使用“设置”,因为我并不总是想以这种方式更新数据库。

我这样做的原因是因为我可能只想调用数据库来更新一列,而不是调用我的保存方法来更新每一列,希望能提高效率。

最佳答案

person.HairColor.Update() 只是意味着 HairColor 属性返回的类型有一个名为 Update 的方法。在你的例子中它看起来像 HairColor 是一个 string,所以要实现你需要为 string 实现一个扩展方法。例如。像

static class StringExtension
{
public static void Update(this string s)
{
// whatever
}
}

但是,我看不出这样做有什么意义。 Update 方法是一个作用于字符串的静态方法,因此它不会影响 Person 实例。 (即使 string 确实有一个 Update 方法,它也与 Person 类型无关)。

我相信您会希望在 Person 上使用 Update 方法,而不是像其他人指出的那样。

关于c# - 有方法的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9915866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com