gpt4 book ai didi

c# - 如何正确模拟 HttpSessionStateBase 中的 KeysCollection?

转载 作者:太空狗 更新时间:2023-10-29 18:08:43 24 4
gpt4 key购买 nike

我在这里的示例中设置了这个模拟 session 对象:How to MOQ an Indexed property

/// <summary>
/// HTTP session mockup.
/// </summary>
internal sealed class HttpSessionMock : HttpSessionStateBase
{
private readonly Dictionary<string, object> objects = new Dictionary<string, object>();

public override object this[string name]
{
get { return (objects.ContainsKey(name)) ? objects[name] : null; }
set { objects[name] = value; }
}
}

一些产生错误的示例代码...

var mockSession = new HttpSessionMock();
var keys = mockSession.Keys;

错误:方法或操作未实现。

我需要实现 Keys 属性,但无法创建 KeysCollection 对象。

执行此操作的最佳方法是什么?

编辑:[解决方案]

我最终根据给出的答案更改了 HttpSessionMock。这就是我最终得到的。 (我还添加了对 System.Linq 的引用)。

internal sealed class HttpSessionMock : HttpSessionStateBase
{
private readonly NameValueCollection objects = new NameValueCollection();

public override object this[string name]
{
get { return (objects.AllKeys.Contains(name)) ? objects[name] : null; }
set { objects[name] = (string)value; }
}

public override NameObjectCollectionBase.KeysCollection Keys
{
get { return objects.Keys; }
}
}

注意:这个模拟 session 将只存储字符串,而不是对象。

最佳答案

我发现原始方法和公认解决方案的组合允许存储对象和实现 keys 属性:

public class HttpSessionMock : HttpSessionStateBase
{
private readonly NameValueCollection keyCollection = new NameValueCollection();
private readonly Dictionary<string, object> objects = new Dictionary<string, object>();

public override object this[string name]
{
get
{
object result = null;

if (objects.ContainsKey(name))
{
result = objects[name];
}

return result;

}
set
{
objects[name] = value;
keyCollection[name] = null;
}
}

public override NameObjectCollectionBase.KeysCollection Keys
{
get { return keyCollection.Keys; }
}
}

关于c# - 如何正确模拟 HttpSessionStateBase 中的 KeysCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com