Assign value to variable
I have this variable, it's an instance of a Interface of a class in business layer. I need to send messages since data access layer, to business layer and finally to presentation layer. I my class "LogBinaryWriter" in data access I have this:
public class LogBinaryWriter : ILogBinaryWriter
{
private readonly IImageLogBuilder _imageLogBuilder;
public void WriteFrameCodes(string filePath, int logSelected)
{
var fileE开发者_运维技巧xists = FileExists(binaryFilePath);
if (fileExists == true)
{
_imageLogBuilder.displayMessage("The file " + binaryFileName + " exist. Dou you want overwrite it? (Y/N)");
}
}
}
I have a message: "the value _imageLogBuilder is never assigned and will always be null"
How can I fix this?
Instantiate an instance of IImageLogBuilder
in your constructor for LogBinaryWriter
and assign it to _imageLogBuilder
. You would have to do it in the constructor since you have _imageLogBuilder
marked as readonly
.
For example, assuming you have a class called MyImageLogBuilder
that implements IImageLogBuilder
:
public LogBinaryWriter()
{
_imageLogBuilder = new MyImageLogBuilder();
}
You could also overload the constructor so you can pass in the IImageLogBuilder
you want to use (lookup constructor injection for more info on this pattern):
public LogBinaryWriter(IImageLogBuilder imageLogBuilder)
{
_imageLogBuilder = imageLogBuilder;
}
Remember, you will need a class that implements the IImageLogBuilder
interface to be able to create a new instance and assign it to the _imageLogBuilder
variable. For example:
public interface IImageLogBuilder
{
void Log(string message);
}
//The class below IMPLEMENTS the IImageLogBuilder interface
public class MyImageLogBuilder : IImageLogBuilder
{
//Implement IImageLogBuilder methods here
public void Log(string message)
{
//Log message
}
}
If you had something like the classes defined above then you could the following in the LogBinaryWriter
constructor and you would no longer get the null reference error.
public LogBinaryWriter()
{
_imageLogBuilder = new MyImageLogBuilder();
}
You need to assign an instance of a class that implements IImageLogBuilder
interface to _imageLogBuilder
field.
Right now your field will always have a value of null
.
For example:
private readonly IImageLogBuilder _imageLogBuilder = new ImageLogBuilder();
perhaps initialize _imageLogBuilder
in constructor ?
public class LogBinaryWriter : ILogBinaryWriter
{
private readonly IImageLogBuilder _imageLogBuilder;
public LogBinaryWriter(IImageLogBuilder imageLogBuilder)
{
_imageLogBuilder = imageLogBuilder;
}
....
}
You never set the value of the _imageLogBuilder
variable. And since you marked it as readonly
, the only place it can be set is in a field initializer, or in a constructor.
Did you mean to do something like this, perhaps?
private readonly IImageLogBuilder _imageLogBuilder = // get the value from somewhere else, or make a new one
精彩评论