Getting type from an object in C#
-
04-10-2020 - |
سؤال
What is wrong in this code? ..
public void gett(object dato, ref object ty)
{
dato = 1; // <- this compiles
Type t = typeof(dato); //<--- here i Got an error
if (t == typeof(int))
{
ty= 1
}
else
{
ty=""
}
}
I got an error "The type or namespace name 'dato' could not be found (are you missing a using directive or an assembly reference?) "
I want to put this VB .net code into c#
Sub getty(ByVal dato As Object, ByRef ty As Object)
If IsDBNull(dato) Then
Select Case ty.GetType.FullName
Case GetType(Integer).FullName
ty = 0
Case GetType(String).FullName
ty = ""
Case GetType(Guid).FullName
ty = New Guid("00000000-0000-0000-0000-000000000000")
Case GetType(DateTime).FullName
Dim da As DateTime = New DateTime(1900, 1, 1)
ty = da
Case Else
ty = ""
End Select
Else
ty = dato
End If
End Sub
Thanks
المحلول
The typeof
operator only works on types. Try dato.GetType()
instead.
نصائح أخرى
To expand upon Mark's answer, dato is not a type, it is a variable. typeof() works on the type (i.e. the class or struct, which in this case is object).
Indeed what you seek is runtime type identification, which you get with dato.GetType().
لا تنتمي إلى StackOverflow