比如:Ticket类中的Distance(只读)属性,如何对其进行赋值?
public class Ticket
{
int _distance;
public int Distance
{
get{return _distance;}
}
}
作者: Darkhorse′Xa 时间: 2014-3-23 13:01
自己写的类的话,可以在类里头对封装的字段赋值.
如果是框架里的类库看看构造函数有没有操作字段的作者: ♠Akechi♠ 时间: 2014-3-23 13:16
public class Ticket
{
private int _distance;
public int Distance
{
set{this._distance = value;}//进行赋值设置
get{return this._distance;}
}
}
当然对值进行一些限定时可以直接在属性里进行,根据不同环境取值
public class Ticket
{
private int _distance;
public int Distance
{
if(value<0)
{
return;
}
set{this._distance = value;}//进行赋值设置
get{return this._distance;}
}
}作者: Doublekill 时间: 2014-3-23 13:24
public class Car
{
public readonly int Height;
}
static void Main(string[] args)
{
Car car = new Car();
FieldInfo fi = car.GetType().GetField("Height");
fi.SetValue(obj, 100); //ok
Console.WriteLine(car.Height); //100
Console.Read();
}
可以实现给只读字段赋值。作者: luoyilan222 时间: 2014-3-23 13:52
final int _distance = 10;