I created a class called CustomData
which uses another one called CustomOptions
as one of its fields. I want to use the CustomData
in a DataTable
as values. Here's a short overview (simplified, the fields are private
and the accessors public
, mostly readonly and the set
is done by custom methods);
enum CustomDataOptionType
{
// Some values, not important
}
class CustomOptions
{
public CustomDataOptionType type { get; }
public Dictionary<string, string> values { get; }
// Some Meth开发者_C百科ods to set the values
}
class CustomData
{
public CustomOptions options { get; }
// Some Methods to set the options
}
So, in the "actual" class that uses the ones above, I create a DataTable
, using columns that are typeof(CustomData)
.
But when I try to access the columns, e.g. by
DataRow Row = data.Rows.Find("bla");
Row["colmn1"].options; // Not possible
Why can't I access the options
-field?
Because the Row["column1"] returns
"object".
You need cast the value to your type:
((CustomData)Row["column1"]).Options.
EDIT: If you want handle the NULL values, you should use this:
CustomData data = Row["column1"] as CustomData;
if ( null != data ) {
// do what you want
}
Or you can use a extension methods for simplify it:
public static DataRowExtensionsMethods {
public static void ForNotNull<T>( this DataRow row, string columnName, Action<T> action ) {
object rowValue = row[columnName];
if ( rowValue is T ) {
action( (T)rowValue );
}
}
}
// somewhere else
Row.ForNotNull<CustomData>( "column1", cutomData => this.textBox1.Text = customData.Username );
You need to cast it into the type CustomData
.
((CustomData)Row["colmn1"]).options
精彩评论