Is generic constructor in non-generic class supported?

后端 未结 3 1458
执念已碎
执念已碎 2020-12-03 09:27

Is it not supported, is it supported but I have to do some tricks?

Example:

class Foo
{
  public Foo(Func f1,Func

        
3条回答
  •  忘掉有多难
    2020-12-03 10:12

    Here is an practical example about how you would like to have extra constructor type parameter, and the workaround.

    I am going to introduce a simple RefCounted wrapper for IDisposable:

    public class RefCounted where T : IDisposable
    {
        public RefCounted(T value)
        {
            innerValue = value;
            refCount = 1;
        }
    
        public void AddRef()
        {
            Interlocked.Increment(ref refCount);
        }
    
        public void Dispose()
        {
            if(InterlockedDecrement(ref refCount)<=0)
                innerValue.Dispose();
        }
    
        private int refCount;
        private readonly innerValue;
    }
    

    This seems to be fine. But sooner or later you would like to cast a RefCounted to RefCounted

提交回复
热议问题