C # inference General subclass type

I have a generic class Proxy<T>and I want to write another generic class with its type parameter being a proxy.

I want to write:

public class MyClass<U> where U : Proxy<T>

but the compiler reports The type or namespace name T could not be found.

The solution I found is to declare it as follows:

public class MyClass<U, T> where U : Proxy<T>

but this seems awkward, as the client will have to declare two types of parameters, for example:

public class SomeClass { ... }
public class SomeProxy : Proxy<SomeClass> { ... }

and then in the client somewhere:

var proxyWrapper = new MyClass<SomeProxy, SomeClass>();

How can I do this without having two types of common type on MyClass. In the end, if we know that the first SomeProxy, then it follows that the second - SomeClass.

+3
source share
6 answers

Maybe something like this will do the job too?

class Test<T> {
    public Test(Proxy<T> proxy) { this.MyProxy = proxy; }
    public Proxy<T> MyProxy { get; private set; }
}
+2
source

IMyClass<SomeProxy> factory , MyClass<SomeProxy, SomeClass>. , , Reflection.

: , . Reflection , , .

, , , ++, , #.

+1

, #, MyClass generic ( .)

+1

, T Myclass, Myclass , -. - , :

public class MyClass<U, T> where U : Proxy<T>

T Myclass, :

public interface IProxy { ... }
public class SomeClass { ... }
public class SomeProxy : Proxy<SomeClass>, IProxy { ... }
public class MyClass<U> where U : IProxy

-:

var proxyWrapper = new MyClass<SomeProxy>();

, T , Type U , .

0

, SomeProxy, , Proxy<T>, :

 T LoadInternal(Identifier id)

, , MyClass, Func<Identifier, T> . Func<Identifier, T> MyClass SomeProxy.

, . , :

public class MyClass<T>{
    private SomeProxy theProxy;

    public MyClass(Func<Identifier, T> loadDelegate){
        theProxy = new SomeProxy(loadDelegate);
    }

    /* Other methods here */

    class SomeProxy : Proxy<T>{
        private Func<Identifier, T> m_loadInternal;

        public SomeProxy(Func<Identifier, T> loadInternal){
            m_loadInternal = loadInternal;
        }

        protected override T LoadInternal(Identifier id){
            return m_loadInternal(id);
        }
    }
}

, , LoadInternal , MyClass, :

var myClass = new MyClass<T>(x => CodeWhichReturnsT());
0

, MyClass. , , SomeProxy, , SomeClass.

, , , , . , , - :

class Proxy<T> 
{ 
    T Value { get; set; }
}
class MyClass<U> where U : Proxy<> { }

Proxy, U. U Proxy, Proxy, , , T, :

class MyClass<U> where U : Proxy<>
{
    void SomeMethod(U parameter)
    {
        var local = parameter.Value;
        //more code here...
    }
}

, compiler local ? , , ​​, , . - , -, U .

-, , . ( , type Proxy), . , CLR , . , , - , , , , .

, , , , , , , .

0

Source: https://habr.com/ru/post/1790001/


All Articles