I have a class that parses in data from a comma delimited text file. I have an enum for the fields to help me parse data in easier. The class that parses all the records in holds public variables for each field, and of course their variable types. I need to get the type of these variables based on the enum given.
public enum DatabaseField : int
{
NumID1 = 1,
NumID2 = 2,
NumID3 = 3,
};
public class DataBaseRecordInfo
{
public long NumID1 { get; set; }
public int NumID2 { get; set; }
public short NumID3 { get; set; }
public static Type GetType(DatabaseField field)
{
Type type;
switch (field)
{
case DatabaseField.NumID1:
type = typeof(long);
break;
case DatabaseField.NumID2:
type = typeof(int);
break;
case DatabaseField.NumID3:
type = typeof(short);
break;
default:
type = typeof(int);
break;
}
return type;
}
};
NumID1, NumID2, NumID3 all get assigned within my constructor. However, I want to get these types without ever creating an instance of DataBaseRecordInfo
. Right now my static method above would work, however, if I wanted to change the variable type, I would have to change it in 2 places. Is there a way to get around having to change this in both places and keep it as a static method?
Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.
C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).
Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.
If the name is always going to match exactly you can do this using reflection.
return typeof(DataBaseRecordInfo)
.GetProperty(field.ToString(), BindingFlags.Public | BindingFlags.Instance)
.PropertyType;
You could even cache these values in a dictionary, so if found, just return the dictionary entry, otherwise determine using reflection and cache the result.
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