开发者

Get concrete Type from Object DataSource and use this type variable in a cast operation

I have a

public object DataSource {get;set} and a public string DisplayMember {get;set}

The object can take everything like an IList or a CustomerListDataSet.

I do not know what the user will set in the DataSource.

I tried this

Type myType = DataSource.GetType().Underlyi开发者_开发技巧ngSystemType;

??? myUnknownObjectInstance = (mytype)DataSource;

I guess it is not possible even with Reflection access a myUnknownObjectInstance.PropertyNameFromDisplayMember and assign it a value like "Peter" ?


Could you refactor the class to use generics? so that you have a datasource of the generic type?


I think you just need DataSource.GetType()


You can determine your type explicitely by a

if (DataSource is IList)
{
 ...
}
else if (DataSource is DataTable)
{
...
}

etc

But if DataSource is not generic, there is no way you can do that cast like you specified. You can cast it, when it type is specified as a parameter.

You can access property by writing

PropertyInfo pi = DataSource.GetType().GetProperty(DisplayMember);
pi.SetValue(DataSource, "Peter");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜