0

I have the following code:

public abstract class EntityMapperBase<T>
{
    protected void Map(string columnName, Func<EntityMapperBase<T>, object> func)
    {
        _mappings.Add(columnName, func);
    }

    protected object GetValueForColumn(string columnName)
    {
       return _mapping[columnName](this);
    }
}

public class PersonMap: EntityMapperBase<PersonMap>
{
    public string Name { get; set; }

    public PersonMap()
    {
        Map(x => ((PersonMap)x).Name);           
    }
}

I would ideally not want to have to cast x to the PersonMap class.

How can I achieve that?

adriaanp
  • 2,064
  • 2
  • 22
  • 40
  • 12
    Suppose `T` is `string`. You're accepting a `Func`. Why would you expect to be able to call that by passing in a `Base`? Perhaps your parameter should be `Func, object>`? What are you trying to achieve? This is a bit of an X-Y problem at the moment. – Jon Skeet Aug 07 '17 at 07:27
  • I'm trying to access the derived class's properties in the function. Like `Test(x => x.Name)`. x is going to be `Base` and then need to cast x to T, trying to prevent that. – adriaanp Aug 07 '17 at 08:38
  • Maybe your method needs to be generic too? Unfortunately, as I said before, you haven't told us what you're actually trying to achieve, so we can't really help you. – Jon Skeet Aug 07 '17 at 08:40
  • Sorry I might have press the enter button before I was completing my thoughts, not sure if you get notified by edits? – adriaanp Aug 07 '17 at 08:42
  • That's still not really enough context. We don't know why `Base` is generic at all, or what your derived classes are doing. Please edit the question to give a lot more information. – Jon Skeet Aug 07 '17 at 08:43

1 Answers1

2

What you are looking for is probably this:

public abstract class Base<T>
{
    public void Test(Func<Base<T>, object> func)
    {
        func(this);
    }
}

Or if you use T as a property inside your Base object:

public abstract class Base<T>
{
    public T MyAwesomeProperty { get; private set; }

    public void Test(Func<T, object> func)
    {
        func(MyAwesomeProperty);
    }
}

T != Base<T>

Why use generics? You can add functions without the type and do the same you are trying to do..

public abstract class EntityMapperBase
{
    protected void Map(string columnName, Func<object> func)
    {
        _mappings.Add(columnName, func);
    }

    protected object GetValueForColumn(string columnName)
    {
       return _mapping[columnName]();
    }
}

public class PersonMap: EntityMapperBase
{
    public string Name { get; set; }

    public PersonMap()
    {
        Map(() => this.Name);           
    }
}
Arcturus
  • 26,677
  • 10
  • 92
  • 107