如何写出这样的类的调用:Class(参数).Property
我是想设计一个“利率”类,其中存放某个时候的利率,比如,7月7号央行加息了,我就用这个类存储数据加息的情况public class IntrestRate
{
public DateTime Date { get;private set; }
public static decimal Demand { get; set; }//活期存款利率
public static decimal Fixed { get; set; }
}
而要使用它,我可这样用:
IntrestRate("20111001").Demand
请大侠帮助设计一下 --------------------编程问答-------------------- 类不会存储什么对象的信息,类是用来设计的。用来存储对象信息的是对象,不是类。而要使用对象,首先要new一个对象实例出来! --------------------编程问答-------------------- IntrestRate("20111001")是方法调用的语法,必须要有类名,所以这样应该是无法实现的,
类似的,可以这样:
IntrestRate.FormString("20111001").Demand
只需要定义一个static FormString 方法
public class IntrestRate
{
public DateTime Date { get;private set; }
public static decimal Demand { get; set; }//活期存款利率
public static decimal Fixed { get; set; }
public static IntrestRate FromString(string strDate)
{
IntrestRate rInstance=new IntrestRate();
rInstance.Date=Convert.ToDatetime(strDate);
return rInstance;
}
}
--------------------编程问答--------------------
谢谢你的回复,我已经按照你的办法实现了我想要的。
过两天结贴,我看有没有其他办法。结贴了就没人回复了,不好意思。 --------------------编程问答-------------------- 你可以使用索引器
public class IntrestRate
{
public DateTime Date { get;private set; }
public static decimal Demand { get; set; }//活期存款利率
public static decimal Fixed { get; set; }
public decimal this[string id] { get { ... } }
}
使用
var x = IntrestRate["20111001"];
--------------------编程问答-------------------- 如果你的 Indexer 返回一个对象,那么就可以继续调用对象的属性了。
比如
public IntrestRate this[string id] { get { return new IntrestRate(); } }
使用
var x = IntrestRate["20111001"].Demand;
--------------------编程问答--------------------
好办法 --------------------编程问答--------------------
好像不行啊,刚试了下 --------------------编程问答-------------------- 我只是告诉你语法。
你的类设计是不合理的。 --------------------编程问答-------------------- IntrestRate”是“类型”,但此处被当做“变量”来使用 --------------------编程问答-------------------- 你应该怎么设计呢?
public class IntrestRate
{
public DateTime Date { get; set; }
public static decimal Demand { get; set; }
public static decimal Fixed { get; set; }
}
然后
List<IntrestRate> list = new List<IntrestRate>
{
new IntrestRate() { Date = DateTime.Parse("2010-09-01"), Demand = 1.2, ... },
new IntrestRate() { Date = DateTime.Parse("2010-09-02"), Demand = 1.2, ... },
...
};
使用:
var x = list.First(x => x.Date.ToString() == "2010-09-01").Demand; --------------------编程问答-------------------- 用索引器的办法还得创建对象 --------------------编程问答-------------------- --------------------编程问答-------------------- 我没看明白。你这个办法好像是将数据存储在List中,要使用数据时随时创建对象。而我的期望是数据存放在数据库中,需要用到的地方很方便地调用,而不要去显示地创建对象。是不是这样啊
--------------------编程问答-------------------- 我是演示,所以创建几个对象。
你从数据库中读取,也是一样的。
补充:.NET技术 , C#