I
Invalidlastname
Hi,
In our project, we used XSD.exe to create the classes, not dataset, which
represent the data entities from xsd files for passing among the tiers.
We want to set the default value for all numeric fields to be -1 in our data
entity classes. I know this can be done by setting the default value
attribute to -1, however, since we created the xsd directly from database
views and in early development stage the schemas changes happened very
often. Some custom set attributes can easily be lost. The solution we came
up is to use reflections to set the default value for all numeric fields,
shown below:
My question is how costly to use Reflection to instantiate an object and
examine every field, and probably assign the value to the field ?
// class DataEntActivator
public static object CreateInstance(System.Type aType)
{
object oDataEnt = Activator.CreateInstance(aType);
FieldInfo[] flds = aType.GetFields();
foreach (FieldInfo fldInfo in flds)
{
if (fldInfo.FieldType == typeof(short))
{
fldInfo.SetValue(oDataEnt , (short)-1);
}
else if (fldInfo.FieldType == typeof(int))
{
fldInfo.SetValue(oDataEnt , -1);
}
}
return oDataEnt ;
}
// calling program
MyDataEntity o =(MyDataEntity)
DataEntActivator.CreateInstance(typeof(MyDataEntity)) ;
// use o as a normal object
In our project, we used XSD.exe to create the classes, not dataset, which
represent the data entities from xsd files for passing among the tiers.
We want to set the default value for all numeric fields to be -1 in our data
entity classes. I know this can be done by setting the default value
attribute to -1, however, since we created the xsd directly from database
views and in early development stage the schemas changes happened very
often. Some custom set attributes can easily be lost. The solution we came
up is to use reflections to set the default value for all numeric fields,
shown below:
My question is how costly to use Reflection to instantiate an object and
examine every field, and probably assign the value to the field ?
// class DataEntActivator
public static object CreateInstance(System.Type aType)
{
object oDataEnt = Activator.CreateInstance(aType);
FieldInfo[] flds = aType.GetFields();
foreach (FieldInfo fldInfo in flds)
{
if (fldInfo.FieldType == typeof(short))
{
fldInfo.SetValue(oDataEnt , (short)-1);
}
else if (fldInfo.FieldType == typeof(int))
{
fldInfo.SetValue(oDataEnt , -1);
}
}
return oDataEnt ;
}
// calling program
MyDataEntity o =(MyDataEntity)
DataEntActivator.CreateInstance(typeof(MyDataEntity)) ;
// use o as a normal object