简体   繁体   中英

Type parameter which inherits from a certain abstract

I was wondering if there is a way to pass in a type which is enforced to be of a certain base type. For instance, for my game engine I have a attribute list (controllable, rigidBody, etc). I have a addAttribute parameter which takes a new object. However, I would like to also have an overload which takes a type instead from which I can create a new object on my own. So for instance

public void addAttribut(Type attribute)

I am thinking of maybe something that implements linq? I have tried but it looks like "where" can be only used on generics:

public void addAttribute(Type attribute) where attribute : Attribute

would be the signature of the function. I believe that Unity does this; however it could be that it can do this through Mono.

I could always throw an exception if it is not of the correct base type. However I was wondering if there is a way to prevent the programmer from passing in the wrong time all together.

Any ideas? Any help is greatly appreciated!

If you're happy for calling code to need to know the type at compile-time , you could make it a generic method with a type parameter:

public void AddAttribute<T>() where T : Attribute
{
    // Use typeof(T)
}

Or to enforce a parameterless constructor which you can then call:

public void AddAttribute<T>() where T : Attribute, new()
{
    T t = new T();
    ...
}

But otherwise there's no way of doing it, no - you'd have to validate the argument at execution time, just like any other.

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