Reputation:
I have a third party party class say Log
. It contains the methods
public void Write(string s, params object[] args)
{
Monitor.Enter(this);
try
{
string logEntry = string.Format(s, args);
this.Write(logEntry);
}
finally
{
Monitor.Exit(this);
}
}
And
public void Write(string LogEntry)
{
this.Write(0, LogEntry);
}
I defined a property outLog
in my own class
public static Log OutLog {get;set;}
I want to use the feature "CallerMemberNameAttribute" etc. in .net 4.5 and override the Write
method as something like:
public void Write(string s,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Monitor.Enter(this);
try
{
string logEntry = string.Format(s, memberName, sourceFilePath, sourceLineNumber);
this.Write(logEntry);
}
finally
{
Monitor.Exit(this);
}
}
So I can call it in my class:
outLog.Write(...);
Not sure how?
Upvotes: 0
Views: 1440
Reputation: 244928
You can't override it, but you can create an extension method (which is signified by the this
keyword on its first parameter) that will do what you want. Something like:
public static class LogExtensions
{
public static void WriteWithCallerInfo(
this Log log,
string s,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Monitor.Enter(log);
try
{
string logEntry = string.Format(s, memberName, sourceFilePath, sourceLineNumber);
log.Write(logEntry);
}
finally
{
Monitor.Exit(log);
}
}
}
With this, you can then write:
OutLog.WriteWithCallerInfo("whatever");
The extension method can't be called just Write
, because normal methods take precedence over extension methods.
Note that I also don't understand the reason for the locking, I think it shouldn't be necessary, assuming the overload Write(int, string)
is thread-safe.
Upvotes: 4
Reputation: 14856
You cannot override non virtual/abstract members.
You can hide but that will only work as long as you use the instance as being an instance of your class. If you use it as being an instance of the base class, it will call the base classe's method.
Upvotes: -1