开发者

VB.NET - I'm Refactoring and Could Use Some Help

开发者 https://www.devze.com 2023-03-31 05:00 出处:网络
I\'m working with vb.net, wcf, wpf and I\'m refactoring working code with the hope of being able to reduce some amount of redundancy. I have a bunch of methods that get called in several places throug

I'm working with vb.net, wcf, wpf and I'm refactoring working code with the hope of being able to reduce some amount of redundancy. I have a bunch of methods that get called in several places throughout the code that only have a slight variation from each other and I would like to replace them with a single method instead.

Specifically, each of the redundant methods process an 1-d array that contain different objects I have created. There are several of these different object types each with different signatures but they have all have a "name" and "Id" property. (Also these objects don't have a shared base class but I could add that if needed.) Each of the redundant methods deal with a different one of the object types.

To refactor the code I would like to pass any of the different object arrays to a single new method that could access the "name" and "id" properties. I'm trying to write this new method in a fashion that wouldn't require me to update it if I created more objects down the road.

I've done some reading on Delegates and Generic Classes but I can't really figure out how this fits in. It would almost be as if I wanted to create a generic class that could handle each of my object types but then somehow also access the "name" and "id" propeties of the different object types.

Any help you can provide would be appretiated. Also, please keep in mind this开发者_C百科 project is written in VB.net.

Thanks Mike


It sounds like having your object implement a common interface or have a shared base class would be best. Interfaces give you the most flexibility down the road if you ever need to pass a class to this method that must derive from some other class that does not implement the interface. However, a base class that implements the interface may also be useful just to reduce the duplicate declarations of these properties.

Public Interface IThingThatHasNameAndId 'good name not included
    ReadOnly Property Name As String
    ReadOnly Property Id As Integer
End Interface

Once you have the interface, you can then pass arrays of types implementing the interface as IEnumerable(Of IThingThatHasNameAndId) or make a generic method taking T() and constrain T to the interface.


Make a base class with the Name and ID properties, then you can make a method that takes in any class that derrives from that class.

Public Function TestFunction(Of t As YourBaseClass)(Byval obj As t) As Boolean

   If obj.Name = "Some Name" AndAlso obj.ID = 1 Then

      Return True

   Else

      Return False

   End If

End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消