I wrote a method in C# which returns Type
and based on this type (which is int or long)
private Type GetNumberColumnType(INumberedEntity entity)
{
var numberRow = SG.Framework.Numbering.NumberingService.NumberableEntities.Where(ne => ne.GetType().FullName == entity.ToString()).FirstOrDefault();
var row = (DataRow)numberRow;
return row.Table.Columns[numberRow.NumberColumnName].DataType;
}
I want to get:
GetNumberColumnType(INumberedEntity entity).MaxValue
instead of:
if( GetNumberColumnType(entity) == typeof(long))
long.MaxValue
else
int.MaxValue
What should I do?
If you don't mind using reflection, here's how you go.
var type = GetNumberColumnType(entity);
FieldInfo fi = type.GetField("MaxValue");
if(fi!=null && fi.IsLiteral && !fi.IsInitOnly)
{
object value = fi.GetRawConstantValue();
}
As noted in comments, reflection is expensive, since these are just constants you can just make a lookup
internal class MaxValueCache
{
private static readonly Dictionary<Type, object> maxValues = new Dictionary<Type, object>()
{
{ typeof(int), int.MaxValue},
{ typeof(long), long.MaxValue}
//...
};
public static object GetMaxValue(Type type)
{
return maxValues[type];
}
}
Then use
var type = GetNumberColumnType(entity);
object value = MaxValueCache.GetMaxValue(type);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With