属性方法?

Mic*_*tes 3 .net c#

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

Person person = new Person(int personID);
person.HairColor = "Blonde";
person.HairColor.Update();
Run Code Online (Sandbox Code Playgroud)

我有特定的属性,我希望能够逐个扩展.我想我可以有一个名为"HairColorUpdate"的方法,但似乎应该可以使用HairColor.Update().我不想使用"set",因为我并不总是希望以这种方式更新DB.

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

Bri*_*sen 8

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

static class StringExtension
{
    public static void Update(this string s)
    {
        // whatever
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我没有看到这样做的意义.该Update方法是一个对字符串起作用的静态方法,因此它不会影响Person实例.(即使string确实有一种Update方法,它与该Person类型无关).

我相信你会想要Update开启这个方法,Person正如其他人所指出的那样.

  • +1只提到"我没有看到这样做的意义." (2认同)