16,555
社区成员
发帖
与我相关
我的任务
分享
using System;
class Demo
{
public static T GetValue<T>(string strText)
{
T t1 = default(T);
if (strText != "")
{
return (T)Convert.ChangeType(strText, typeof(T));
}
return t1;
}
static void Main(string[] args)
{
DateTime d = GetValue<DateTime>("2007-5-14");
Console.WriteLine(d);
int i = GetValue<int>("5");
Console.WriteLine(i);
}
}
Imports System
Class Demo
Public Shared Function GetValue(Of T)(ByVal strText As String) As T
Dim t1 As T = Nothing
If strText <> "" Then
Return DirectCast(Convert.ChangeType(strText, GetType(T)), T)
End If
Return t1
End Function
Private Shared Sub Main(ByVal args As String())
Dim d As DateTime = GetValue(Of DateTime)("2007-5-14")
Console.WriteLine(d)
Dim i As Integer = GetValue(Of Integer)("5")
Console.WriteLine(i)
End Sub
End Class
Imports System
Class Test
Private Shared Sub Main()
Console.WriteLine(Max(1))
' 输出: 1
Console.WriteLine(Max(0.3, -0.5))
' 输出: 0.3
Console.WriteLine(Max(0D, -3D, 3.14D))
' 输出: 3.14
Console.WriteLine(Max(9F, -1F, 3.14F, -2.718F))
' 输出: 9
Console.WriteLine(Max(0, 23, 3114, 120718, 5678))
' 输出: 120718
End Sub
Private Shared Function Max(Of T As {Structure, IComparable})(ParamArray x As T()) As System.Nullable(Of T)
If x.Length = 0 Then
Return Nothing
End If
Dim a As T = x(0)
For Each i As T In x
If a.CompareTo(i) < 0 Then
a = i
End If
Next
Return a
End Function
End Class
using System;
class Test
{
static void Main()
{
Console.WriteLine(Max(1)); // 输出: 1
Console.WriteLine(Max(.3, -.5)); // 输出: 0.3
Console.WriteLine(Max(0M, -3M, 3.14M)); // 输出: 3.14
Console.WriteLine(Max(9f, -1f, 3.14f, -2.718f)); // 输出: 9
Console.WriteLine(Max(0u, 23u, 3114u, 120718u, 5678u)); // 输出: 120718
}
static T? Max<T>(params T[] x)
where T: struct, IComparable
{
if (x.Length == 0) return null;
T a = x[0];
foreach (T i in x)
if (a.CompareTo(i) < 0) a = i;
return a;
}
}