static void Main(string[] args)
{
Say<string>("abc");
}
public static T Say<T>(string str)
{
T t1 = default(T);
t1 = (T)str;
return t1;
}为什么一直报无法从string类型转换为T呢?
如果一个泛型方法的返回值就是T本身 而且在方法内部对传进来的参数进行操作然后返回 怎么写呢?
{
Say<string>("abc");
}
public static T Say<T>(string str)
{
T t1 = default(T);
t1 = (T)str;
return t1;
}为什么一直报无法从string类型转换为T呢?
如果一个泛型方法的返回值就是T本身 而且在方法内部对传进来的参数进行操作然后返回 怎么写呢?
{
T t1 = default(T);
t1 = (T)((object)str);
return t1;
}
这一句,你当然无法保证str能转换成功,
T如果是int呢这函数逻辑就不对
{
return (T)Convert.ChangeType(str,typeof(T));
}
{
Say<string>("abc");
}
public static T Say<T>(string str)
{
T t1 = default(T);
t1 = (T)Convert.ChangeType(str,t1.GetType());
return t1;
}
public class MyList<TElement> where TElement : class
{
private object[] array = new object[10]; public int Length { get; private set; } public MyList() {
Length = 0;
} public void Add(TElement element) {
if(Length + 1 > array.Length) {
object[] newArray = new object[array.Length + 10];
array.CopyTo(newArray, 0);
array = newArray;
}
Length++;
array[Length - 1] = element;
} public TElement this[int i] {
get {
return array[i] as TElement;
}
set {
array[i] = value;
}
}
}
@SuppressWarnings("unchecked")
public <T extends Object> T add(T a, T b) throws Exception {
if (a instanceof Integer && b instanceof Integer) {
Integer c = (Integer) a + (Integer) b;
return (T)((Object)c);
}else if(a instanceof String && b instanceof String){
String c = (String) a + (String) b;
return (T)((Object)c);
}else{
throw new MyException("add");
}
}}
package pensonal.zeng;public class FanxingMethodDemo {
public static void main(String[] args) throws Exception {
FanxingMethod fm = new FanxingMethod();
int a = fm.add(new Integer(8), new Integer(9));
System.out.println(a);
String s = fm.add("8", "a");
System.out.println(s);
}}
呃,用这个解决自己正做的例子可以: