VB.NET中的泛型函数 [英] Generic Functions in VB.NET

查看:505
本文介绍了VB.NET中的泛型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对泛型(概念或语法)一般不太熟悉(在集合中不使用它们,也没有),但我想知道以下是完成我想要的最佳方式。实际上,我并非完全正面的泛型将解决我在这种情况下的问题。



我在NHibernate中建模和映射了几十个对象,并且需要某种通用类用于我的CRUD操作,而不是为每种类型创建一个独立的persister类..例如

  Sub Update(someObject as Object ,objectType as String)
Dim session As ISession = NHibernateHelper.OpenSession
Dim transaction As ITransaction = session.BeginTransaction
session.Update(ctype(someObject,objectType))
transaction。 Commit()
End Sub

其中someObject可以是不同的类型。我知道这不是做这件事的最好方式(或者它甚至可以工作),但我希望有人能引导我朝着正确的方向前进。

解决方案

这里的关键问题是:session.Update作为参数是什么?如果session.Update允许一个泛型对象,那么我只是使用它:

  Sub Update(Of T)(ByVal someObject作为T)
Dim session as ISession = NHibernateHelper.OpenSession
Dim transaction As ITransaction = session.BeginTransaction
session.Update(someObject)
transaction.Commit()
End Sub

这会将泛型类型T传递给session.Update。

如果session.Update只需要一个对象,那么只需传入该对象;不需要CType。另外,如果objectType(string)只是当前对象的类型名称,那么最好先使用someObject.GetType()。


I'm not too familiar with generics (concept or the syntax) in general (short of using them in collections and what not), but I was wondering if the following is the best way of accomplishing what I want. Actually, I'm not entirely positive generics will solve my problem in this case.

I've modelled and mapped a few dozen objects in NHibernate, and need some sort of universal class for my CRUD operations instead of creating a seperate persister class for each type.. such as

Sub Update(someObject as Object, objectType as String)
     Dim session As ISession = NHibernateHelper.OpenSession
     Dim transaction As ITransaction = session.BeginTransaction
     session.Update(ctype(someObject, objectType))
     transaction.Commit()
End Sub

where someObject can be different types. I know this isn't the best way of doing this (or if it'll even work) but I'm hoping someone can steer me in the right direction.

解决方案

The key issue here is: What does session.Update take as a parameter? If session.Update allows a generic object, then I'd just use that:

 Sub Update(Of T)(ByVal someObject As T)
     Dim session As ISession = NHibernateHelper.OpenSession
     Dim transaction As ITransaction = session.BeginTransaction
     session.Update(someObject)
     transaction.Commit()
 End Sub

That'll flow the generic type T through to session.Update.

If session.Update just takes an object, then just pass in the object; no need to CType it. Additionally, if objectType (string) is just the type name of the current object, you'd be better off using someObject.GetType() in the first place.

这篇关于VB.NET中的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆