Generic method gets parameter type from superclass

I have a problem with a typed method in C #. I want to call an inherited method of an object. This method calls a static method with the "this" parameter. The parameter of the static method is general. Now I want the generic type of this parameter to be the type of the first object. But a parameter is always a type of abstract class.

Here is an example:

abstract class AbstractClass
{
    bool update()
    {
        Connection.Update(this);
    }
}

class Entity : AbstractClass
{
}

class Connection
{
    public static void Update<T>(T obj)
    {
        someMethod<T>()
    }
}

If I try to do:

Entity foo = new Entity();
foo.update();

Connection.Update will look like this in the debugger:

public static void Update<AbstractClass>(AbstractClass obj)
{
    someMethod<AbstractClass>()
}

But I want this:

public static void Update<Entity>(Entity obj)
{
    someMethod<Entity>()
}

Is there a possibility of something like

someMethod<typeof(obj)>()

or anything else to solve my problem?

+4
source share
6 answers

T, Entity. , child, Update. @ Alexander - , T-, AbstractClass

abstract class AbstractClass<T>
where T: AbstractClass<T> //restrict T as a child of AbstractClass<T>
{
    bool update()
    {
        Connection.Update<T>(this as T);
    }
}

class Entity : AbstractClass<Entity>
{
}

class Connection
{
    public static void Update<T>(T obj)
    {
        someMethod<T>()
    }
}
0

, :

abstract class AbstractClass<T>
{
    bool update()
    {
        Connection.Update<T>(this as T);
    }
}

class Entity : AbstractClass<Entity>
{
}

class Connection
{
    public static void Update<T>(T obj)
    {
        someMethod<T>()
    }
}
+3

, this dynamic, . .

public bool update()
{
    Connection.Update((dynamic)this);
    return true;
}

:

public interface IEntityVisitor
{
    void Visit(EntityBase entity);
    void Visit(Entity entity);
}

public interface IEntity
{
    void Accept(IEntityVisitor visitor);
}

public abstract class EntityBase : IEntity
{
    public virtual void Accept(IEntityVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class Entity : EntityBase
{
    public override void Accept(IEntityVisitor visitor)
    {
        visitor.Visit(this);
    }
}
+1
var genericType = typeof(Connection<>);
var specificType = genericType.MakeGenericType(typeof(Entity));
var conn = Activator.CreateInstance(specificType);
0

Any thing someMethod<typeof(obj)>()doesn’t seem to exist, because it violates the security of C # types, because the compiler cannot know the type of parameter execution. However, you can get a true type object by calling obj.GetType(). You can use this type object to dynamically call methods using Reflection.

0
source

One solution:

abstract class AbstractClass
{
    bool update<T>()
    {
        Connection.Update(T);
    }
}

then

Entity foo = new Entity();
foo.update<Entity>();
0
source

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


All Articles