'Accessing a public member from within a generic method
I'm trying to have some toolbox with each tool in that toolbox being something quite different in functionality. So every tool would require its own config to be created and passed at the start, or when you need to change params, while the base class would be just the general outline of what all the tools have in common, but I'm getting an error when trying to access a public member of some config from a generic method. I have something like this:
public abstract class Tool
{
public abstract void Setup<T>(T setupParams);
}
public class SomeTool : Tool
{
public class SomeConfig
{
public int counter;
public float size;
public SomeConfig(int _counter, float _size)
{
counter = _counter;
size = _size;
}
}
int m_counter;
int m_size;
public override void Setup<SomeConfig>(SomeConfig setupParams)
{
m_counter = setupParams.counter;
//'SomeConfig' does not contain a definition for 'counter' and no accessible extension
// method 'counter' accepting a first argument of type 'SomeConfig' could be found
// (are you missing a using directive or an assembly reference?)
}
}
Having a constructor, or non generic setup function works, but why am I getting an error with what I am doing here?
Solution 1:[1]
When you do this:
public abstract void Setup<T>(T setupParams)
You are using <T>
to define the type. That type doesn't exists. T
isn't a class. You can put any name and compile:
public override void Setup<WhatEver>(WhatEver setupParams)
But WhatEver
is a type that you define just there. It doesn't exists.
You can define the class in this form:
public abstract class Tool<T>
{
public abstract void Setup(T setupParams);
}
public class SomeConfig
{
public int counter;
public float size;
public SomeConfig(int _counter, float _size)
{
counter = _counter;
size = _size;
}
}
public class SomeTool : Tool<SomeConfig>
{
int m_counter;
int m_size;
public override void Setup(SomeConfig setupParams)
{
m_counter = setupParams.counter;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Victor |