1
How could I create a method that doesn’t need to receive a type as a parameter, just a string
, but would return a type?
For example:
public static T Guard(string guard_name) where T : class, IAuth
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
Instead of:
public static T Guard<T>(string guard_name) where T : class, IAuth
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
Then the call would go like this: Auth.Guard("users")
instead of Auth.Guard<users>()
.
I need a method that receives only a string and not a type because I am working with a class ActionFilterAttribute
that the statement is [Autorized(string guard_name)]
and so I can’t use a type on that occasion. I’ve even tried variations like [Autorized<users>]
for example, but being about an attribute I could not.
It is possible?
Yes, it is possible, but not as you are trying. Are you having any problems trying to do this? Your feedback does not seem to be using the
T
. You can put more parts of this method?– Maniero
It was a basic example, I’ll edit.
– Rafael Alexandre
Okay, I’ve edited the code.
– Rafael Alexandre
Now I understand better, I think it is not possible not. I will think of something to see if it can.
– Maniero
I added a comment about what my difficulty is, maybe there is another way instead of creating a method that takes a string and returns a type.
– Rafael Alexandre
The question has improved nicely. Yeah, I’m struggling with something different, exactly this doesn’t work, I think the only way is to give up the generic type, which you don’t want, right? Generic I’m pretty sure it’s impossible. If it is, you’ll have to go for a walk, maybe it won’t even make up for.
– Maniero
I agree, but if there is no way I will have to give up the generic type, the problem is that I would lose the "dynamic", I would have to declare a new Auth for each type of users...
– Rafael Alexandre
Generic type works well for almost the entire application, only on
ActionFilterAttribute
that I lose that possibility, maybe I create a new method to be worked only there.– Rafael Alexandre
I think I would have to think of a slightly different solution. It is possible that I have a generic solution, but it will be quite complex. Return a
object
and then make a cast probably won’t solve your problem.– Maniero