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;

不编译。该方法仅适用于 alatedObject 的类(通过引用),并且在技术上应该是可能的。例如,当使用"out T[]"作为参数来分配泛型数组时,它工作得很好。有没有可行的语法?

三个问题

首先,你忘记了括号。

allocatedObject = new T;

应该是

allocatedObject = new T();

其次,需要new()通用约束:

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

应该是

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

第三 - 这仅适用于公共无参数构造函数!真的没办法。如果您有需要构造参数的对象,或者通过静态方法和私有构造函数分配的对象,那么您就是 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.RegisterType<MyClass>
  (
    c => AllocateMemory(() => new MyClass())  //Register for IoC
  );

DotNetFiddle的工作示例

最新更新