A general class in which a type can process strings

I want to create a generic class in which a class type can handle strings.

I want to use this class for any class that has a static Parse (string) function, like System.Int32, System.Double, but also for classes like System.Guid. All have a static Parse function.

Thus, my class needs a where clause, which restricts my generic type to types using the Parse function

I would like to use it as follows:

class MyGenericClass<T> : where T : ??? what to do ???
{
     private List<T> addedItems = new List<T>()

     public void Add(T item)
     {
          this.AddedItems.Add(item);
     }

     public void Add(string itemAsTxt) 
     {
         T item = T.Parse(itemAsTxt);
         this.Add(item);
     }
}

What to write in the where clause?

+6
source share
3 answers

I was unhappy with the answers that would use reflection for analysis.

, , Parse.

, . , , . , , ,

, , , Parse, T

class MyGenericClass<T>
{
    public MyGenericClass(Func<string, T> parseFunc)
    {
         this.parseFunc = parseFunc;
    }

    private readonly Func<string, T> parseFunc;

    public void Add(string txt) 
    {
        this.Add(parseFunc(txt));
    }
}

:

MyGenericClass<Guid> x = new MyGenericClass<Guid>(txt => Guid.Parse(txt));
MyGenericClass<int> y = new MyGenericClass<int> (txt => System.Int32.Parse(txt));

,

+5

, , ?

    static void Main(string[] args)
    {
        Guid g = DoParse<Guid>("33531071-c52b-48f5-b0e4-ea3c554b8d23");

    }

    public static T DoParse<T>(string value) 
    {
        T result = default(T);
        MethodInfo methodInfo = typeof(T).GetMethod("Parse");
        if (methodInfo != null)
        {

            ParameterInfo[] parameters = methodInfo.GetParameters();
            object classInstance = Activator.CreateInstance(typeof(T), null);

            object[] parametersArray = new object[] { value };
            result = (T)methodInfo.Invoke(methodInfo, parametersArray);

        }
        return result;
    }
+1

. , . , .

, , , - . , :

class MyType
{
    void Parse() { ... }
}

, , - say - int.Parse(myString) and myInstanceOfMyType.Parse() `.

. item? , . , methpd, .

:

var types = allAssemblies.SelectMany(x => x.GetTypes())
                .Where(x => x.GetMethod("Parse") != null);

, AmbiguousMatchException, , .

0

All Articles