开发者

Converting Generic Type into reference type after checking its type using GetType(). How?

i am trying to call a function that is defined in a class RFIDeas_Wrapper(dll being used). But when i checked for type of reader and after that i used it to call function it shows me error Cannot convert type T to RFIDeas_Wrapper.

EDIT

private List<string> GetTagCollection<T>(T Reader)
            {
                TagCollection = new List<string>();
                if (Reader.GetType() == typeof(RFIDeas_Wrapper))
                {

                    ((RFIDeas_Wrapper)Reader).OpenDevice(); 
                    // here Reader  is of type RFIDeas_Wrapper
                    //, but i m开发者_如何学C not able to convert Reader into its datatype.

                    string Tag_Id =  ((RFIDeas_Wrapper)Reader).TagID();
                    //Adds Valid Tag Ids into the collection
                    if(Tag_Id!="0")
                        TagCollection.Add(Tag_Id);
                }
                else if (Reader.GetType() == typeof(AlienReader))
                    TagCollection = ((AlienReader)Reader).TagCollection;

                return TagCollection;
            }

((RFIDeas_Wrapper)Reader).OpenDevice();

((AlienReader)Reader).TagCollection;

I want this line to be executed without any issue. As Reader will always be of the type i m specifying. How to make compiler understand the same thing.


One trick is to use object in the middle to force it:

if (Reader is RFIDeas_Wrapper)
{
    ((RFIDeas_Wrapper)(object)Reader).OpenDevice(); 
    ...
}

or use as:

RFIDeas_Wrapper wrapper = Reader as RFIDeas_Wrapper;
if (wrapper != null)
{
    wrapper.OpenDevice();
    ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜