The way is to declare TRYPARSECONSTRAINT as an interface, and then you
write classes that implement it...

But I think you want to use this constraint for already declared
types.... (int32 and Dobule comes to mind)  that's a bit of duck
typing, I may suggest to move to VB, but I'm more like to say:

Join Microsoft Connect [https://connect.microsoft.com/default.aspx]

And request better and powerful contraints for the next C#, I've done
some suggestions on the matter, and I would like to see more comments
and other suggestion like the mines, I hope microsoft notices that we
may do a great use of this, My thinking is: with better interfaces and
better generic contraints there is no need for duck typing, and
without duck typing as a threat there is not a reason to risk the type
safety we all know and luv from C#.

Of course you may still use reflection (as I do below), or move to VB
as I said earlier. And by doing so, letting microsoft add to C# things
we don't asked for, and that we will need to learn how and when to use
(if we ever use them).

I'll do the charity anyway (it's ugly, it's slow, it's hard to
understand, needs a try statement, but it works)
[dynamic in C# 4.0 will do this more beautiful, less hard to
understand, but equally slow, better generics and interfaces may do it
faster, more beautiful, easy to understand, and more important: secure
(no try statement)]

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Reflx
{
    class Program
    {
        static void Main(string[] args)
        {
            var P = new Program();
            Console.WriteLine(P.GetValueFromString<int>("123"));
            Console.ReadKey();
        }
        public T GetValueFromString<T>(string Data)
        {
            try
            {
                var p = new ParameterModifier(2);
                p[0] = false;
                p[1] = true;
                var info = new object[] { Data, default(T) };
                typeof(T).InvokeMember("TryParse",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
null, null, info, new ParameterModifier[]{p}, null, null);
                return (T)info[1];
            }
            catch{}
            return default(T);
        }
    }
}

Reply via email to