简体   繁体   中英

How to pass and use a generic object in c#?

I have multiple methods that each return an Object.

public objA myCall(string[] args)
{           
    webAPI myAPI = new webAPI();
    returnData = myAPI.callApi("http://localhsot/api", args , "POST");

    XmlSerializer serializer = new XmlSerializer(typeof(myObj));

    using (TextReader reader = new StringReader(returnData))
    {
        objA result = (objA)serializer.Deserialize(reader);

        return result;
    }
}

And

public objB myCall(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(myObj));

  using (TextReader reader = new StringReader(returnData))
  {
      objB result = (objB)serializer.Deserialize(reader);

      return result;
  }
}

What I would like to do is consolidate these into one method using generics. This way I can pass in the object that I would like returned. I've never used generics before and need a little help. This is what I have tried:

public T myCall<T>(ref T myObj, string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(myObj));

  using (TextReader reader = new StringReader(returnData))
  {
      myObj result = (myObj)serializer.Deserialize(reader);

      return result;
  }
}

But when I put this into Visual Studio, I get get an error saying that "myObj" is a variable but is used like a type. If you have had experience with this and are willing to help, I would appreciate it.

You are almost there

public T myCall<T>(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(T));

  using (TextReader reader = new StringReader(returnData))
  {
      T result = (T)serializer.Deserialize(reader);

      return result;
  }
}

And then you call it by passing the type as the generic constraint.

var result = myCall<objA>(someArguments);

On a side note (and also my opinion) objA is not a good name for a type.

You should remove from parameters myObj and change it in the body of method to T like this

public T myCall<T>(string[] args)
{           
  webAPI myAPI = new webAPI();
  returnData = myAPI.callApi("http://localhsot/api", args , "POST");

  XmlSerializer serializer = new XmlSerializer(typeof(T));

  using (TextReader reader = new StringReader(returnData))
  {
      T result = (T)serializer.Deserialize(reader);

      return result;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM