gpt4 book ai didi

.net - 如何使用泛型方法替换重复的属性?

转载 作者:行者123 更新时间:2023-12-04 18:04:41 25 4
gpt4 key购买 nike

目前我的代码具有以下属性:

  Private _queueRetriever As Services.IQueueRetriever
Public ReadOnly Property QueueRetriever As Services.IQueueRetriever
Get
If _queueRetriever Is Nothing Then
RemotingSetup.RegisterHttpBinaryChannel()
_queueRetriever = RemotingFactory.CreateProxy(Of Services.IQueueRetriever)(Options.DevLocal)
End If

Return _queueRetriever
End Get
End Property

Private _queueCountRetriever As Services.IQueueCounter
Public ReadOnly Property QueueCounter As Services.IQueueCounter
Get
If _queueCountRetriever Is Nothing Then
RemotingSetup.RegisterHttpBinaryChannel()
_queueCountRetriever = RemotingFactory.CreateProxy(Of Services.IQueueCounter)(Options.DevLocal)
End If

Return _queueCountRetriever
End Get
End Property

如您所见,这两个属性的代码基本相同。只是类型不同。我在泛型方法方面不是很有经验,但我觉得我应该能够使这段代码更加 DRY使用泛型。可以做到还是这不是通用方法的工作?

编辑

根据 Marc 的回答,我得出以下结论:

  Protected Services As New Dictionary(Of Type, Object)

Protected Function CreateService(Of T)() As T
If Not Services.ContainsKey(GetType(T)) Then

RemotingSetup.RegisterHttpBinaryChannel()
Services.Add(GetType(T), RemotingFactory.CreateProxy(Of T)(Options.DevLocal))

End If

Return DirectCast(Services(GetType(T)), T)
End Function

当然可以这样使用:

Me.CreateService(Of IService).Foo()

最佳答案

你可以这样做(并为切换到 C# 道歉,但我的 VB 技能在这里缺乏微妙之处 - 我确信它在 VB 中也能正常工作)

private T GetProxy<T>(ref T field) where T : class {
if(field == null) {
RemotingSetup.RegisterHttpBinaryChannel();
field = RemotingFactory.CreateProxy<T>(Options.DevLocal);
}
return field;
}

与:

private Services.IQueueCounter queueCounter;
public Services.IQueueCounter QueueCounter {
get { return GetProxy(ref queueCounter); }
}
private Services.IQueueRetriever queueRetriever;
public Services.IQueueRetriever QueueRetriever {
get { return GetProxy(ref queueRetriever); }
}

关于.net - 如何使用泛型方法替换重复的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878347/

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