简体   繁体   中英

Generic parameter type

I have a question concerning a generic type parameter.

Let's say I have the following definitions in my domain model:

abstract class Entity<TId>
{
    public TId Id { get; private set; }
    /* ... */
}

class Person : Entity<long>
{
    public string Name { get; set; }
    /* ... */
}

Let's say now I want to create a method to view details of a person:

public void Details(long? id)
{
    if (!id.HasValue) {
        Error(...);
        return;
    }
    var person = PersonRepository.Get(id.Value);
    ShowPersonDetail(person);
}

Let's go further and say that PersonRepository is an specialization of Repository , so that its "Get" method is "automagically" implemented, to accept the correct strong-typed id argument (in this case, a long argument).


Now let's say one day I decide that Person's Ids should be Guids . What I want is to be able to change this ONLY in my Person class, and it will change everywhere else automatically. If I do so, in the code I have right now, the PersonRepository.Get() method won't need to be edited, but my Details() method will have to be changed.

I was looking for something like:

Details(Person.IdType id) { /*...*/ }

Oh, by the way, this "Details" method will be located in another assembly, if this might change anything...

but strongly-typed and it must accept either value types or reference types.

Any ideas?

Thanks!

I'm not exactly sure if this is what you want. You can have the method take a Func<Person,T> and have it infer the types for you:

public T Get<T>(Func<Person,T> property) {
    return property(myPerson);
}

and call it with:

var id = PersonRepository.Get(p => p.Id);

The compiler is able to infer type of T from the lambda expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM