Hey I have the following two classes:
public class YoloCocoP7Model : YoloModel
{
public override int Width { get; set; } = 640;
public override int Height { get; set; } = 640;
public YoloCocoP7Model()
{
}
}
public class YoloScorer<T> : IDisposable where T : YoloModel
{
public YoloScorer(string weights, SessionOptions opts = null) : this()
{
_inferenceSession = new InferenceSession(File.ReadAllBytes(weights), opts ?? new SessionOptions());
}
}
Now I can call a function like this:
public YoloScorer<YoloCocoP7Model> _scorer;
I want to change the Width and Height inside the YoloCocoP7Model class and Initialize it to the YoloScorer class and tried it the following way:
var test = new YoloCocoP7Model();
test.Width = 10;
test.Height = 10;
This works but however If I want to use that changed class then with:
var _scorer = new YoloScorer<test>;
I get an error saying "test" is a "variable" but is used like "Type".
How can I use the changed Class then?
CodePudding user response:
The YoloScorer<T>
in your class definition is a generic class, meaning it can work for different types.
You can now implement methods with that type like public T GetNewObject()
or public string[] GetAllPropertyNames<T>()
that use that Type T
.
The type is, however, not the object itself, it's the type of object. In your case, the type is YoloCocoP7Model
. The type has no instance.
If you want to give your class YoloScorer
a object YoloCocoP7Model
, you need to declare a member of that type and add it, i.e. via constructor:
public class YoloScorer : IDisposable
{
public YoloModel Model {get; set;};
public YoloScorer(YoloModel model) : this()
{
Model = model;
}
}
Then, you can modify it by calling
var _scorer = new YoloScorer<test>;
_scorer.Model.Width = 1337;
CodePudding user response:
Adding <T>
to a class makes it generic. That means it can work with values of different types. For instance, the List
class you might have used before is generic. It can store elements of any types you provide it with.
Therefore, when you want to create a list of type int
, for instance, you type new List<int>()
.
Now, the class you defined is also generic. That means, when you create an instance of it with new YoloScorer<...>()
, you create a new YoloScorer
that works with objects of type ...
. This is not exactly what you want, from my understanding.
Instead, you want to pass the specific YoloCocoP7Model
to this class. To do that, just add a parameter corresponding to it to the constructor:
public YoloScorer(string weights, YoloCocoP7Model model, SessionOptions opts = null)
Now you can access model
from the inside (and probably store it in some sort of private variable to make it accessible at later stages). From my understanding, your class does not need to be generic (<T>
is not necessary).