English 中文(简体)
• 如何建立一般性回归案例的通用方法?
原标题:How to create generic method which return instance of generic?

我想要创建简单的工厂级,实施这样的接口:

IFactory 
{
   TEntity CreateEmpty<TEntity>(); 
}

In this method I want to return an instance of type TEntity (generic type). Example:

TestClass test = new Factory().CreateEmpty<TestClass>(); 

是否可能? 接口是否正确?

我试图这样做:

private TEntity CreateEmpty<TEntity>() {
   var type = typeof(TEntity);
   if(type.Name =="TestClass") {
      return new TestClass();
   }
   else {
     ...
   }
}

但它没有汇编。

最佳回答

您需要具体说明<代码>new(对通用参数的限制

public TEntity CreateEmpty<TEntity>() 
    where TEntity : new()
{
    return new TEntity();
}

The new constraint specifies that the concrete type used must have a public default constructor, i.e. a constructor without parameters.

public TestClass
{
    public TestClass ()
    {
    }

    ...
}

如果你根本不具体指明任何建筑商,那么该建筑群就会有一个公共违约建筑商。

我们不能宣布<代码>新(限值)。 如果你需要通过参数,那么你必须为此宣布一种专用方法,例如确定适当的接口。

public interface IInitializeWithInt
{
     void Initialize(int i);
}

public TestClass : IInitializeWithInt
{
     private int _i;

     public void Initialize(int i)
     {
         _i = i;
     }

     ...
}

贵工厂

public TEntity CreateEmpty<TEntity>() 
    where TEntity : IInitializeWithInt, new()
{
    TEntity obj = new TEntity();
    obj.Initialize(1);
    return obj;
}
问题回答
interface IFactory<TEntity> where T : new()
{
   TEntity CreateEmpty<TEntity>(); 
}

这种方法将帮助你,按照这一顺序通过参数,在其中,这些参数是:

private T CreateInstance<T>(params object[] parameters)
{
    var type = typeof(T);

    return (T)Activator.CreateInstance(type, parameters);
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签