如何仅使用System.Type / reflection来引用泛型单例实例

时间:2014-04-29 19:15:26

标签: c# generics singleton

我创建了一个简单的性能测试类,它是一个单一的,它使用泛型PerformanceTesting<T>.Instance

(我的博客文章中提供了完整的源代码,但它不是最新版本http://www.createdbyx.com/post/2013/03/27/Code-Snippets-12-%E2%80%93-Performance-Testing.aspx

这允许开发人员使用他们更习惯使用的内容作为访问者密钥,无论是字符串,整数还是枚举等。

所以一切都运行良好,但我正在尝试构建一个性能报告窗口,我希望能够从PerformanceTesting<int> or PerformanceTesting<string>等所有实例化的单个实例中收集性能数据。

我认为我能做到的唯一方法是使用反射。我还要提一下,PerformanceTesting类使用另一个类来跟踪用作PerformanceTesting<T>单例的访问键的各种类型。

    /// <summary>
    /// Provides a lock object when a singleton reference need to be instantiated.
    /// </summary>
    private static object lockObject = new object();

    /// <summary>
    /// Gets a singleton instance of the <see cref="PerformanceTesting{T}"/> class.
    /// </summary>
    public static PerformanceTesting<T> Instance
    {
        get
        {
            if (singleton == null)
            {
                lock (lockObject)
                {
                    singleton = new PerformanceTesting<T>();
                    PerformanceTestingTypes.Register<T>(); 
                }
            }

            return singleton;
        }
    }

PerformanceTestingTypes类的简化版本是......

public class PerformanceTestingTypes
{
    private static PerformanceTestingTypes singleton;
    private List<Type> types = new List<Type>();

    public static PerformanceTestingTypes Instance
    {
        get
        {
            return singleton ?? (singleton = new PerformanceTestingTypes());
        }
    }

    public static Type[] GetTypes()
    {
        var values = new Type[Instance.types.Count];
        Instance.types.CopyTo(values, 0);
        return values;
    }

    public static void Register<T>()
    {
        Instance.types.Add(typeof(T));
    }

    // can't return PerformanceTesting<T> because T is of System.Type not the actual accessor type.
    public static PerformanceTesting<T> GetTesting<T>(T type)
    {
        var rootType = typeof(PerformanceTesting<>); // this is wrong but placed for example purposes!!!

        var prop = rootType.GetProperty("Instance");
        var reference = prop.GetGetMethod().Invoke(null, null);

        return reference; // compile error because Invoke returns type System.Object
    }
}

我正在使用此方法尝试将结果报告给调试日志...

   /// <summary>
    /// If the PERFORMANCE symbol is available will report the performance metric information out to the console.
    /// </summary>
    public static void ReportPerformanceTimes()
    {
        var result = string.Empty;
        foreach (var type in PerformanceTestingTypes.GetTypes())
        {
             var perf = PerformanceTestingTypes.GetTesting(type);

            var keyNames = PerformanceTestingTypes.GetKeyNames(type);

            foreach (var name in keyNames)
            {
                var key = PerformanceTestingTypes.ConvertKey(name, type);
                result += string.Format("{0} - Total: {1}ms Average: {2} Count: {3}\r\n", name, perf.TotalMilliseconds(key), perf.AverageMilliseconds(key), perf.GetStartCount(key));
            }

            result += string.Format("Total Performance Times - Total: {0}ms", perf.TotalMilliseconds(perf.GetKeys()));
        }

         Debug.Log(result);
    }

我的问题我在PerformanceTestingTypes.GetTesting()方法中有谎言。我需要仅使用System.Type返回对泛型单例的特定实例的引用,该System.Type引用单例使用的实际类型作为其访问者密钥。

var type = typeof(int); // the accessor key type that was used
// from the 'type' variable get a reference to singleton 
var reference = PerformanceTesting<int>.Instance;

或者换句话说,如果我所拥有的是一个变量'type',那么我将如何使用反射来获取PerformanceTesting<int>的类型,这是一个引用int的System.Type。

从技术上讲,我认为我可以尝试在字符串中创建和构建单个C#类,然后将该字符串编译成内存程序集,然后调用该类以获取对我需要的单例的引用,但这似乎有点过分了我怀疑我可能遇到相同或类似的问题以及铸造。

这是可能的还是我想做不可能的事?希望我的问题有道理。我的大脑决定在这个问题上中断。 :(

2 个答案:

答案 0 :(得分:0)

试试这个:

var performanceTestingType = typeof(PerformanceTesting<>);
Type[] typeArgs = { typeof(int) };
var genericType = performanceTestingType.MakeGenericType(typeArgs);
object performanceTestingOfTypeInt = Activator.CreateInstance(genericType);

MSDN文章here

答案 1 :(得分:0)

对于那些登陆此页面寻找类似答案的人,我正在通过jaywayco的答案为我如何实现目标提供最终方法。

    private void DrawPerformanceMetricsFlatList()
    {
        foreach (var type in PerformanceTestingTypes.GetTypes())
        {
            var performanceTestingType = typeof(PerformanceTesting<>);
            Type[] typeArgs = { type };
            var genericType = performanceTestingType.MakeGenericType(typeArgs);

            var data = genericType.GetProperty("Instance", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public).GetGetMethod().Invoke(null, null);
            var totalMilli = data.GetType().GetMethod("TotalMilliseconds", new[] { type });
            var avgMilli = data.GetType().GetMethod("AverageMilliseconds", new[] { type });
            var totalTicks = data.GetType().GetMethod("TotalTicks", new[] { type });
            var avgTicks = data.GetType().GetMethod("AverageTicks", new[] { type });
            var startCount = data.GetType().GetMethod("GetStartCount", new[] { type });
            var fromConverter = data.GetType().GetProperty("ConvertFromStringCallback");
            // var toConverter = data.GetType().GetProperty("ConvertToStringCallback", new[] { type });
            var func = fromConverter.GetGetMethod().Invoke(data, null);
            var invoker = func.GetType().GetMethod("Invoke");

            var keyNames = PerformanceTestingTypes.GetKeyNames(type);

            switch (this.sortIndex)
            {
                case 1:
                    keyNames = keyNames.OrderBy(x => x).ToArray();
                    break;

                case 2:
                       keyNames = keyNames.OrderByDescending(x => totalTicks.Invoke(data, new[] { invoker.Invoke(func, new[] { x }) })).ToArray();
                    break;

                case 3:
                         keyNames = keyNames.OrderByDescending(x => avgTicks.Invoke(data, new[] { invoker.Invoke(func, new[] { x }) })).ToArray();
                    break;

                case 4:
                        keyNames = keyNames.OrderByDescending(x => startCount.Invoke(data, new[] { invoker.Invoke(func, new[] { x }) })).ToArray();
                    break;
            }

            ControlGrid.DrawGenericGrid((items, index, style, options) =>
            {
                var value = items[index];
                var selected = GUILayout.Toggle(this.selectedIndex == index, value, style);
                if (selected)
                {
                    this.selectedIndex = index;
                    var key = invoker.Invoke(func, new[] { value }); 
                    this.performanceData = string.Format("{0}\r\nTotal: {1}ms ({4} ticks)\r\nAverage: {2}ms ({5} ticks)\r\nCount: {3}\r\n", value,
                        totalMilli.Invoke(data, new[] { key }),
                        avgMilli.Invoke(data, new[] { key }),
                        startCount.Invoke(data, new[] { key }),
                        totalTicks.Invoke(data, new[] { key }),
                        avgTicks.Invoke(data, new[] { key }));
                }
                return value;
            }, keyNames, 1, GUI.skin.button);
        }
    }