开发者

How do I store a reference to a generic type created based on an expression passed to the method?

开发者 https://www.devze.com 2023-03-10 22:57 出处:网络
I have the following method, which returns a generic object of type INamedProperty<TReturn> based on the return type of a defined expression. I need to store a reference to the object that is re

I have the following method, which returns a generic object of type INamedProperty<TReturn> based on the return type of a defined expression. I need to store a reference to the object that is returned by this method for future processing. What type should I store it as? Would Object be OK开发者_C百科? How would I cast it back to the appropriate INamedProperty<TReturn> later on? Do I also need to store the type of TReturn?

public class PropertyBuilder<T> : IPropertyBuilder<T> where T : class {
    public INamedProperty<TReturn> Named<TReturn>(Expression<Func<T, TReturn>> property) {
        o = new NamedProperty<TReturn>();
        // how do I store o as an instance of the encapsulating class?
    }
}

Thanks in advance!


I would try to implement a generic, uhh, non-generic INamedProperty that could implement the operations you need:

interface INamedProperty
{
    // Informational
    Type ContainingType { get; }
    string Name { get; }
    Type ReturnType { get; }

    // Operations (for example)
    void CopyTo(object obj, INamedProperty property);
}

Then implement them in the generic NamedProperty:

class NamedProperty<T> : INamedProperty { ... }


Why not take an additional Action parameter instead of storing a reference? You're running into trouble because TReturn doesn't really exist in a concrete form outside the context of your method's execution; think more functional programming and less procedural.

edit: added code sample

public INamedProperty<TReturn> Named<TReturn>(Expression<Func<T, TReturn>> property, Action<INamedProperty<TReturn>> action)
{
    var o = new NamedProperty<TReturn>();
    action.Invoke(o);
    return o;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号