Scott Hanselman's blogに基づいてVBでToCSV()拡張を書き込もうとしています。それは私のC#のVBには正しくないことがありますが、それはすべて正しいようです。パブリックメンバ 'ToCSVValue'タイプの 'Integer'がVB拡張メソッドで見つかりません
Dim s As String = ctx.Customers.Where(Function(x) x.CustomerID = 123456).Select(Function(x) New With {.CustomerID = x.CustomerID, .CustomerName = x.CustomerName}).ToCSV()
それがうまく機能ToCSVに取得します。私のようなもので、それを呼び出す
<System.Runtime.CompilerServices.Extension>
Public Function ToCSV(Of T)(items As IEnumerable(Of T)) As String
Try
Dim csvBuilder = New StringBuilder()
Dim properties = GetType(T).GetProperties()
For Each item As T In items
'' Test Code
Dim newline As String = ""
For Each l2 As Reflection.PropertyInfo In properties
' This works
newline &= l2.GetValue(item, Nothing)
' This works too
Dim int As Integer = 1234
Dim s As String = int.ToCSVValue()
'This works
Dim nl = l2.GetValue(item, Nothing)
' This blows up with "Public member 'ToCSVValue' on type 'Integer' not found."
' The Debugger type shows "Object {Integer}" which I assume to mean that the debugger interprets the object as an integer.
nl = nl.ToCSVValue()
Next
' Original code
Dim line As String = String.Join(",", properties.Select(Function(p) p.GetValue(item, Nothing).ToCSVValue()).ToArray())
csvBuilder.AppendLine(line)
Next
Return csvBuilder.ToString()
Catch ex As Exception
Throw
End Try
End Function
<System.Runtime.CompilerServices.Extension>
Private Function ToCSVValue(Of T)(item As T) As String
If item Is Nothing Then
Return """"""
End If
If TypeOf item Is String Then
Return String.Format("""{0}""", item.ToString().Replace("""", "\"""))
End If
Dim dummy As Double
If Double.TryParse(item.ToString(), dummy) Then
Return String.Format("{0}", item)
End If
Return String.Format("""{0}""", item)
End Function
: は、私はモジュールを追加しました。それは渡された項目を認識します。最初の項目を引き出し、その中に2つの項目があることがわかります。すべていいよ!
GetValue()はうまく動作します。
静的な整数を作成し、ToCSVValueを呼び出すと正常に動作します。 静的な文字列を作成し、ToCSVValueを呼び出すと正常に動作します。
GetValue()でToCSVValueを呼び出すと、次のようになります。 パブリックメンバ 'ToCSVValue'が 'Integer'型で見つかりません。
同様に、データセットに文字列がある場合は、 タイプ 'String'のパブリックメンバー 'ToCSVValue'が見つかりません。
理想的には、これは「オリジナルコード」のセクションと同じように機能し、この他のすべてのテストコードを強制終了できます。
何が起こっているのか、「(Of T)」がGet GetValue()型を処理していない理由を教えてもらえますか?
をうーん...わからないがなぜなら、あなたが 'ToCSVValue(nl)'を使用すると動作します – Slai
あなたは正しいです。このように動作します。しかし、どうやって意図どおりに動作させることができますか? 'foo.ToCSV()' –