MSDN-WhiteKnight / CilTools

A set of tools to work with CIL in .NET applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support generic constraints

MSDN-WhiteKnight opened this issue · comments

using System;
using System.Collections.Generic;
using System.Text;
using CilTools.BytecodeAnalysis;

namespace CilToolsTest
{
    class Program
    {
        public static T Sum<T>(T x,T y) where T:struct
        {
            if (typeof(T) == typeof(int))
            {
                int res = (Convert.ToInt32(x) + Convert.ToInt32(y));
                return (T)Convert.ChangeType(res, typeof(int));
            }
            else if (typeof(T) == typeof(float))
            {
                float res = (Convert.ToSingle(x) + Convert.ToSingle(y));
                return (T)Convert.ChangeType(res, typeof(int));
            }
            else throw new NotSupportedException();
        }

        static void Main(string[] args)
        {
            Console.WriteLine(CilAnalysis.MethodToText(typeof(Program).GetMethod("Sum")));
            Console.ReadKey();
        }
    }
}

Current output:

.method   public hidebysig static !!T Sum<T>(
    !!T x,
    !!T y
) cil managed
// ...

Expected output:

.method public hidebysig static !!T  Sum<valuetype .ctor ([mscorlib]System.ValueType) T>(
     !!T x,
     !!T y
) cil managed
// ...