C# 中的泛型内存分配

Generics memory allocation in C#

可以使用如下方法在 C# 中集中分配内存:

    public static void AllocateMemory<T>(out T allocatedObject)
    {
        try
        {
            allocatedObject = new T;
        }
        catch (System.OutOfMemoryException e)
        {
            allocatedObject = null;

            SignalFailureOfMemoryAllocation("Generic memory error " + e.ToString());
        }
    }

但是,行

 allocatedObject = new T;

不编译。该方法仅适用于 类(通过引用)作为 allocatedObject,技术上应该是可行的。它运作良好,例如当使用 "out T[]" 作为参数来分配泛型数组时。有可用的语法吗?

三个问题

首先,你忘记了括号。

allocatedObject = new T;

应该是

allocatedObject = new T();

其次,需要new() generic constraint:

public static void AllocateMemory<T>(out T allocatedObject)

应该是

public static void AllocateMemory<T>(out T allocatedObject) where T: new()

第三——这只适用于 public 无参数构造函数!真的没有办法解决这个问题。如果你有需要构造参数的对象,或者通过静态方法和私有构造函数分配的对象,你就是S.O.L.

一种不同的方法

也许尝试传递 Func<T>。更强大了。

public static T AllocateMemory<T>(Func<T> func) 
{
    try
    {
        return func();
    }
    catch (System.OutOfMemoryException e)
    {
        Console.WriteLine("Generic memory error " + e.ToString());
        return default(T);
    }
}

并这样称呼它:

var o = AllocateMemory(() => new MyClass());  //Default constructor

var o = AllocateMemory(() => new MyClass(arg1, arg2));  //Constructor with parameters

var o = AllocateMemory(() => SomeFactory.Instantiate<MyClass>()); //Using a factory class

甚至(如果您使用 IoC container):

container.RegisterType<MyClass>
  (
    c => AllocateMemory(() => new MyClass())  //Register for IoC
  );

Working example on DotNetFiddle