简体   繁体   中英

Is it possible to reference a generic class object without specifying its type?

I have this generic class:

public class Grid<TGridObject> {

    public int Width { get; set; }
    public int Height { get; set; }
    public float CellSize { get; set; }
}

I want to create another class called GridDebugger , its role is to draw lines and texts based on the settings and content of the Grid class. So ultimately i would have something like this:

public class GridDebugger {
    
        private Grid<TGridObject> grid
        public void DebugGrid(){
         //debug the grid
        }
    }

The problem is that of course i cannot declare with TGridObject cause it doesn't exists in the current content, i can change that line to:

private Grid<bool> grid

And now that i have a grid of bool i can debug it, but i want to have a generic gridDebugging class that can work with any grid type.

Is this possible?

Thank you

Do you mean the code below?

public class GridDebugger<TGridObject> {
    
        private Grid<TGridObject> grid
        public void DebugGrid(){
         //debug the grid
        }
    }

Given that you want to debug any grid type with the GridDebugger it sounds like you might be better off with a generic DebugGrid method than a generic grid member.

public class GridDebugger
{
    //stuff
    public void DebugGrid<TGridObject>(Grid<TGridObject> grid) { //stuff }
}

At that point you can debug a grid of any type with the same GridDebugger as long as no logic is specific to the type of the TGridObject .

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