gpt4 book ai didi

c# - c# 是否提供了一种直接的方法来为属性名称起别名?

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

c#(任何版本)是否提供了一种改进的属性名称别名方法?在 AccountBase 中,我使用字符串 Username 来标识帐户,但在 NonstandardAccount 中,我希望客户端(API 的使用者)使用 CustomerNumber 来防止混淆。

这是我的代码:

public abstract class AccountBase
{
public string Username { get => Username; set => Username = value; }
}

public class StandardAccount
{
// The username is the ID
}


public class NonstandardAccount : AccountBase
{
// The Username or CustomerNumber is the ID
public string CustomerNumber { get => Username; set => Username = value; }

// OR ideally, but I don't think this works
public string CustomerNumber => Username;
}

我可以放弃添加 CustomerNumber 属性,只记录它与用户名相同,但不清楚。我可以让我的实现保持原样,但为了清晰起见而额外存储可能不是一个好的权衡。

最佳答案

感谢 Patrick Artner,我不仅找到了答案,而且找到了理想的答案。它一直在我的源代码中是正确的,但我不相信我的直觉。

public class NonstandardAccount : AccountBase
{
// Does work and works perfectly! Username is still accessible
public string CustomerNumber => Username;
}

一个新的惨痛教训:仅仅因为你的直觉在很多情况下都是错误的,并不意味着你应该诋毁它是一个病态的说谎者。

关于c# - c# 是否提供了一种直接的方法来为属性名称起别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730917/

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