Define a generic variable without defining the type

Asked

Viewed 499 times

3

I’m doing some tests on Unity so I can practice programming. I’m new and this question can be kind of stupid. I want to know if this is possible:

I created the following abstract class:

public abstract class Variable<T> : ScriptableObject {}

And I want to use this class as a variable that will accept children of that class:

private Variable<Int> variable;

But I want the variable to accept children of any kind and not just the declared something like:

private Variable variable;

That’s possible?

  • It would not be the case to use var?

  • Unity only accepts c# 2.0 cannot use var :/

  • @Valterluiz I suggest you read here and also watch the video about ScriptableObject.

  • @Valterluiz Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

1

So you don’t want to use Generics. This mechanism is to have a specific type.

In any case I could use a object who is the type of all kinds. I would avoid that, it’s almost never fitting in and is probably making a bad choice of how to architect your application.

It may be that you need to change the type at runtime, then you should use dynamic, but I would avoid it even more.

If you do not know how to use these mechanisms very well the application will become unstable.

It would be nice to understand about typing.

It seems to me that this heritage is also wrong, but I can not say only with what has in the question.

  • I did some tests here and Object helped, it just doesn’t seem functional. I had already taken a look at Dynamic and rather tried to avoid it. What I was trying to do is very simple I have two classes: public class FloatVariable : ScriptableObject&#xA;{&#xA; private float value;&#xA;&#xA; public void AddValue(float amount)&#xA; {&#xA; value += amount;&#xA; }&#xA;&#xA;} And another which is basically the same thing only structured in Int . :)

  • I could try to help more, but the question doesn’t have enough information, the way it is doesn’t need any of this stuff, but I don’t know, it could be because the description of the bad problem.

0

Dude, in this case, you can use inheritance, with a superclass or an interface, and as you identify common needs, you’ll assign the interface/Superclass.

I think it can help, another option is the same Object, because it is the base of the types.

I hope I helped, if I said something silly I’m sorry!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.