I have a method that iterates through an object's properties and sets the values to their type's default values. Some properties are enums. I have another function that gets the default value of the enum (not 0), but it requires passing the enum type which is not known in the current method.
[DefaultValue(Red)]
public enum Colors
{
Red = 1,
green = 2
}
// In another class
public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
{
Type t = typeof(TEnum);
DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return (TEnum)attributes[0].Value;
}
else
{
return default(TEnum);
}
}
public static void ClearObject<T>(object obj)
{
obj = (T)obj;
PropertyInfo[] props = obj.GetType().GetProperties();
string propName = "";
try
{
foreach (PropertyInfo pi in props)
{
propName = pi.Name;
Type t = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
if (t.IsEnum)
{
// This works
// var val = EnumFunctions.GetDefaultValue<Colors>();
var val = EnumFunctions.GetDefaultValue<t>();
pi.SetValue(obj, val);
}
// In case of nullable value types int,datetime, etc - set null
else if (Nullable.GetUnderlyingType(pi.PropertyType) != null)
pi.SetValue(obj, null);
else
pi.SetValue(obj, null, null);
}
}
catch (Exception e)
{
string msg = $"Error for {propName}: {e.Message}";
throw new Exception(msg);
}
}
I've tried typeof(t), t.GetType().
I want the default value for a Colors enum property to be Red. The line causing the error is var val = EnumFunctions.GetDefaultValue(); Error CS0118 't' is a variable but is used like a type
Aucun commentaire:
Enregistrer un commentaire