5
I intend to make a generic method that receives a enum[]
and that a string representing the items of array comma-separated.
public static string ToSeparatedCommaString<T>(T[] enums)
where T : struct, IComparable, IFormattable, IConvertible//Não garante que seja enum mas sempre limita alguma coisa
{
var commaString = string.Empty;
foreach (var item in enums)
{
commaString += ((Enum)item).GetStringValue() + ",";
}
return commaString.TrimEnd(',');
}
The problem arises when I want to access Extension Method GetStringValue()
.
The attempt to make cast, as expected, is not allowed.
Is there any way to get this?
GetStringValue()
is a method that returns a string the value of which is indicated in the attribute associated with the enum
What is extension method is
GetStringValue()
. The error control was to be added later. In this case it doesn’t make much sense to be extension method because it only applies toenum[]
.– ramaral
There’s no guarantee that the guy
T
is Enum. Then the warranty must be via code.– Miguel Angelo
I understand... but even if it’s not extension method, it’s still good to check that guy
T
really beEnum
, because if it is not, an exception will occur when doing the type-cast forEnum
.– Miguel Angelo
Of course, as I said above, this verification was scheduled to be made.
– ramaral
I was researching a solution that used
Enum.ToObject()
but its solution is simpler. I only have the question of why the method existsEnum.ToObject()
if the simple cast for Object works.– ramaral
The
Enum.ToObject
serves to convert an integer into aEnum
given theType
of that one:Enum.ToObject(typeof(MeuEnum), 123)
. The return already leaves Boxed with the typeobject
. This method exists because you will not always have the type of Enum statically, only a Type object.– Miguel Angelo
I have improved the LINQ version to make it more readable.
– Miguel Angelo
The LINK is more readable to those who dominate it well, which is not yet my case!
– ramaral
I took the @bigown test on the LINQ version... it is clearly the most horrible of all... 3.5x slowest. So feel free not to use LINQ!
– Miguel Angelo