且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将此代码段从C#转换为VB.net

更新时间:2022-10-16 12:06:59

这样的事情应该有效:

 公共 可覆盖  Sub  ReadRecordFromDb( Of  T  As   Class )( ByVal  ID 正如 整数
...

' 通过检查IsPrimaryKey找到主键字段名称
Dim pk As String = dataMembers。 Single 函数(m)m.IsPrimaryKey).Name

' 返回id参数与主键字段值匹配的单个对象
Dim tbl 正如 T = table.SingleOrDefault( Function (t2)
Dim memberId As String = t2。 GetType ()。的getProperty(p k).GetValue(t, Nothing )。ToString()
返回 memberId == ID .ToString()
结束 功能

...
结束 Sub


这个解决方案看起来很有希望,但在我将==更改为单个=后,我得到了错误

't'已经被声明为此方法的类型参数。

函数(t)中的t突出显示为错误。



如果我将t更改为另一个字母然后我得到错误

语句lambdas无法转换为表达式树



我认为我仍然缺少一些简单的语法。


我放弃并在一个单独的项目中将它保存在C#中并从VB项目调用它


I'm able to convert the PK line but not the following in my VS 2010 project. I've looked at expression trees, lambdas, etc. but haven't gotten anything to work yet. The automated tools I've found online don't convert it correctly. Any help would be appreciated.

public virtual void ReadRecordFromDB<T>(Int32 ID) where T : class
{


...

// find the primary key field name by checking for IsPrimaryKey
string pk = (dataMembers.Single<MetaDataMember>(m => m.IsPrimaryKey)).Name;

// return a single object where the id argument matches the primary key field value
var tbl = table.SingleOrDefault<T>(delegate(T t)
{
    String memberId = t.GetType().GetProperty(pk).GetValue(t, null).ToString();
    return memberId.ToString() == ID.ToString();
});

Something like this should work:
Public Overridable Sub ReadRecordFromDb(Of T As Class)(ByVal ID As Integer)
    ...
    
    ' find the primary key field name by checking for IsPrimaryKey
    Dim pk As String = dataMembers.Single(Function (m) m.IsPrimaryKey).Name
    
    ' return a single object where the id argument matches the primary key field value
    Dim tbl As T = table.SingleOrDefault(Function (t2)
        Dim memberId As String = t2.GetType().GetProperty(pk).GetValue(t, Nothing).ToString()
        Return memberId == ID.ToString()
    End Function)
    
    ...
End Sub


This solution looked promising but after I changed the == to a single =, then I got the error
"'t' is already declared as a type parameter of this method."
The t inside the Function(t) is highlighted as the error.

if I change the t to another letter then I get the error
"Statement lambdas cannot be converted to expression trees"

I'm still missing something simple with the syntax, I think.


I gave up and kept it in C# in a separate project and called it from a VB project