c# 是否提供直接为 属性 名称起别名的方法?
Does c# offer a direct way to alias a property name?
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#(任何版本)是否提供改进的方法来为 属性 名称起别名?在 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;
}
一个新的惨痛教训:仅仅因为你的直觉在很多情况下都是错误的,并不意味着你应该诋毁它是一个病态的说谎者。