c# - 将类属性绑定到实例属性
问题描述
我的假设场景:
在新世界秩序中,单一政府要求所有银行向其客户提供相同的利率。所以所有银行都应该同意利率。此外,银行需要制定一项政策,可以改变(增加或减少)利息或不改变利息。如果(至少)一家银行不愿改变利率,则在谈判成功之前不得修改利率。
我的 C# 程序如下所示
namespace NewWorldOrder
{
public class Bank
{
public static float rate;
private bool allow_rate_modification;
private string bankname;
// Property
public string Bankname
{
// Assume some Business Logic is added to filter values
// Omitting those for brevity
get => bankname;
set => bankname = value;
}
// Property
public bool AllowRateModification
{
// Assume some Business Logic is added to filter values
// Omitting those for brevity
get => allow_rate_modification;
set => allow_rate_modification = value;
}
static Bank()
// To set the static field at runtime
{
// In actual case, this value may be initialized from a db
// Again doesn't matter how it is initialized.
rate = 4.5f;
}
// The ctor
public Bank(string bank_name_, bool allow_modification)
{
Bankname = bank_name_;
AllowRateModification = allow_modification;
}
}
class Program
{
static void Main(string[] args)
{
Bank rbs =new Bank("Royal Bank of Scotland",true);
Bank lloyds = new Bank("LLoyds", true);
Bank hsbc = new Bank("HSBC", false);
Bank.rate = 4.7f; // This should not happen as HSBC is not open to rate change
// Irrelevant Stuff
// ...
// ...
}
}
}
长话短说 :
静态(类)属性如何绑定到所有实例中的一个特定(通常是布尔值)实例属性。或者在 C# 中是否有另一种逻辑方法可以做到这一点?
注意:我(非常)是 C# 新手,所以如果这完全是错误,请原谅我
解决方案
听起来你需要一个列表,linq可以帮你查询
var list = new List<Bank>()
{
new Bank("Royal Bank of Scotland", true),
new Bank("LLoyds", true),
new Bank("HSBC", false)
};
if (list.All(x => x.AllowRateModification))
{
// all banks Allow Rate Modification
}
你可以使用一个类来管理银行
public class Exchange
{
public List<Bank> Banks { get; set; } = new List<Bank>();
public void NegotiateRates()
{
while (!CanModifyRates)
{
// to the rate stuff in here
}
}
public bool CanModifyRates => Banks.All(x => x.AllowRateModification);
}
...
private static void Main()
{
var exchange = new Exchange();
exchange.Banks.Add(new Bank("Royal Bank of Scotland", true));
exchange.Banks.Add(new Bank("LLoyds", true));
exchange.Banks.Add(new Bank("HSBC", false));
exchange.NegotiateRates();
}
其他资源
表示可以通过索引访问的对象的强类型列表。提供搜索、排序和操作列表的方法。
Enumerable.All(IEnumerable, Func) 方法
确定序列的所有元素是否满足条件。
推荐阅读
- python - 在查询参数中过滤或排序 API 请求
- python - 两个列表的积分没有给出预期的结果
- r - 如何将两列整数转换为一列日期,以便将其绘制在图表上
- angular - fullcallendar 的角度选择器不起作用
- python - 如何在不重新启动机器的情况下修复 torch.cuda.is_available() False 问题?
- python - 当函数需要大数据结构作为参数时,如何有效地使用 Pool.starmap?
- vue.js - 如何以编程方式滚动元素而不是 vuetify 中的页面
- java - 为什么在 rDao.insert(log) 处出现未处理的 SQL 异常?
- google-cloud-platform - 如何为 GKE Ingress 分配静态 IP?
- python-3.x - Python:函数调用中的重复序列