gpt4 book ai didi

c# - 如何提取使用 "using"关键字且一次性的方法

转载 作者:行者123 更新时间:2023-11-30 14:52:02 30 4
gpt4 key购买 nike

我有大约 20 个方法,其中大部分需要 UserPrincipalExtension 一次性类来执行一些不同的操作,我想将其提取到一个单独的方法中,但我不确定如何,

public static UserPrincipalExtension GetUPE(Identity type, string identity)
{
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension UPE = UserPrincipalExtension.FindByIdentity(pc, type, identity))
{
// do different operations
// if I return UPE here then would pc going to dispose itself ?
}

// how best to return UPE and dipose pc as well, return UPE;
}

所以我可以像这样在其他方法中使用它:

var UPE = GetUPE(IdentityType.SID, "S-32sldkfjsldr344");
using(UPE)
{

}

UPEPrincipalContext 应该放在后面。

最佳答案

除非 UPE 有自己的方式来处理主体上下文,否则您基本上有两个选择 - 在 UPE 周围创建一个包装类,或者使用辅助函数。

关于包装类方法几乎没有什么可说的 - 只需拥有一个具有 PC 和 UPE 字段的类,并使用其 Dispose 方法处理两者。根据您的要求,公开 UPE,或公开您需要的方法。最简单的示例可能是这样的:

class UpeWrapper : IDisposable
{
public readonly PrincipalContext PrincipalContext;
public readonly UserPrincipalExtension UserPrincipalExtension;

public UpeWrapper(PrincipalContext principalContext,
UserPrincipalExtension userPrincipalExtension)
{
this.PrincipalContext = principalContext;
this.UserPrincipalExtension = userPrincipalExtension;
}

public void Dispose()
{
try
{
UserPrincipalExtension.Dispose();
}
finally
{
PrincipalContext.Dispose();
}
}
}

使用辅助函数稍微少一点样板:

void UseUserPrincipalExtension(Identity type, string identity, 
Action<UserPrincipalExtension> action)
{
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension UPE =
UserPrincipalExtension.FindByIdentity(pc, type, identity))
{
action(UPE);
}
}

而且用法也很简单:

UseUserPrincipalExtension
(
a, b,
upe =>
{
// Do your work here
}
);

关于c# - 如何提取使用 "using"关键字且一次性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689228/

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