I am trying to get the fields of the 开发者_开发知识库current class. I make the class implement the ICloneable
Interface.
Inside the clone()
the following line doesn't seem to find any fields. Why though?
foreach (FieldInfo fi in this.GetType().GetFields())
{
}
Many Thanks,
That will only find public fields. Look at BindingFlags
.
To suggest a better way, just call MemberwiseClone
, it will copy all the fields values in the current class/instance.
Because only public fields are returned by default. Use the other overload with BindingFlags.NonPublic
.
Use BindingFlags
as:
var flags = BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Public;
foreach (FieldInfo fi in this.GetType().GetFields(flags))
{
//...
}
GetFields returns all the public fields of the current Type. http://msdn.microsoft.com/en-us/library/ch9714z3.aspx You may need http://msdn.microsoft.com/en-us/library/6ztex2dc.aspx
Well the only reason why GetFields would be empty is if "no public fields are defined for the current Type" (from MSDN).
More generally, did you know that there already exists a protected method in the Object class that already does what you're trying to do (a shallow copy)? It's called MemberwiseClone
You could use it like this:
public object Clone()
{
return MemberWiseClone();
}
精彩评论