mardi 21 mai 2019

How to invoke a method in a C# generics class

I am new to C# generics. I have several classes with identical methods. I want to create a generic class which will be of type belonging to any of those classes and invoke the methods from them. I am not sure whether this is possible, or there is a different way of doing it. I have given my code sample below. I have included two representative classes named, EastCoastStores and WestCoastStores. When I try to invoke the method using reflection, I am getting null reference exception for GetMethod("GetZipCode") in the GetZipCode() method of the MyGenerics class. I have searched the internet, but could not an appropriate solution.

//Two classes with identical methods
public class EastCoastStores
{
    private string zip;

    public void SetZipCode(string zip)
    { this.zip = zip; }

    public string GetZipCode()
    { return zip; }
 }

public class WestCoastStores
{
    private string zip;

    public void SetZipCode(string zip)
    { this.zip = zip; }

    public string GetZipCode()
    { return zip; }
}

//Generic class which can accept either of the above classes
public class MyGenerics<T>
{
    private T selectedValues;
    public MyGenerics(T selectedValues)
    {
        this.selectedValues = selectedValues;
    }
    public String GetZipCode()
    {
        Type typeParameterType = typeof(T);
        var getZipCode = typeParameterType.GetMethod("GetZipCode");
        var val = 

typeParameterType.GetType().GetMethod("GetZipCode").Invoke(typeParameterType, 
 null);
        return val.ToString();
    }
}

//Accessing the class method
public static void Main(string[] args)
    {
        EastCoastStores eastCoastStores = new EastCoastStores();
        eastCoastStores.SetZipCode("12345");
        MyGenerics<EastCoastStores> orderAction = new 
  MyGenerics<EastCoastStores>(eastCoastStores);
        var val = orderAction.GetZipCode();

    }





Aucun commentaire:

Enregistrer un commentaire