C#装饰类使用默认类版本的方法 [英] C# Decorator Class using Default Class Version of Method
问题描述
如果尝试装饰一个类,你如何保持与默认实现相同的方法?
How do you leave a method the same as the default implementation if trying to decorate a class?
例如,我正在尝试向IWebDriver接口添加一个属性的WebDriver类。
For example I am trying to add a property to a IWebDriver interface of the WebDriver class.
ie
public class MyWebDriver : IWebDriver
{
private IWebDriver _driver;
internal string _currentTest { get; set; }
internal MyWebDriver(IWebDriver driver)
{
_driver = driver;
}
}
Visual Studio IntelliSense让我实现了类(或接口)与一堆'抛出新的NotImplementedException();
作为默认WebDriver类方法的方法体。
Visual Studio IntelliSense had me implement the class (or interface) with a bunch of 'throw new NotImplementedException();
as the method body for the default WebDriver class methods.
ie
public IWebElement FindElement(By by)
{
throw new NotImplementedException();
}
我的问题是如果我不想调整这些方法的行为我该怎么实现呢?我只是把它全部留在身体里,或者我必须举例说明(如果是这样,FindElement方法有一个返回类型和参数呢?):
My question is if I don't want to adjust the behavior of these methods at all how do I implement that? Do I just leave it all as that line in the body or do I have to for example (if this is the case how would it be done for the FindElement method w/ a return type and parameter?):
public string CurrentWindowHandle
{
get
{
return _driver.CurrentWindowHandle;
}
}
public ReadOnlyCollection<string> WindowHandles
{
get
{
return _driver.WindowHandles;
}
}
public void Close()
{
_driver.Close();
}
public void Quit()
{
_driver.Quit();
}
我只是尝试向IWebDriver界面添加一个字符串变量来跟踪其中测试正在运行。
I am just trying to add a string variable to the IWebDriver interface to keep track of which test is running.
编辑:我找到了一个替代解决方案,我的初始问题(这是正确记录测试结果),不涉及实现任何新功能,
I found an alternative solution to my initial problem (which was proper logging of test results) that does not involve implementing any new functionality but rather placing try/catches in the correct places.
这个问题的解决方案可以在标记的答案以及下面的其他地方找到@AlexanderWinter显示一个例子
The solution to this question can be found in the marked answer as well as further below where @AlexanderWinter shows an example of an implementation including a way to retrieve data globally.
感谢您的帮助。
推荐答案
而不是扩展类,使用外部方式保存数据。您可以使用的是 系统.Runtime.CompilerServices.ConditionalWeakTable< TKey,TValue>
。
Instead of extending the class, use external means to save the data. Something you can use is System.Runtime.CompilerServices.ConditionalWeakTable<TKey, TValue>
.
您可以使用以下方式:
class TestState
{
public string Name { get; set; }
}
//initialization of some private field
ConditionalWeakTable<IWebDriver, TestState> myTestsByDriver = new ConditionalWeakTable<IWebDriver, TestState>();
...
//usage:
myTestsByDriver.GetOrCreateValue().Name = "My_First_Test";
//etc.
这篇关于C#装饰类使用默认类版本的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!