我有这样的函数,它得到一个typeof T,加密属性(所有属性都是字符串):
private T Cipher(T item)
{
var t = item.GetType();
//get all properties of item and put in a list
var props=new List<PropertyInfo>(t.GetProperties());
var vals= props.Select(propertyInfo =>
propertyInfo.GetValue(item).ToString()).ToList();
var cipher = new List<string>();
foreach (var val in vals)
{
cipher.Add(CipherString.Encrypt(val,"key");
}
有没有办法用新值cipher
创建一个新的T型属性?
编辑:T是具有一些属性的类定义
答案 0 :(得分:0)
获取属性后,您可以执行此操作而不是获取值
var ciphered = Activator.CreateInstance<T>();
foreach (var property in props)
property.SetValue(ciphered, CipherString.Encrypt(property.GetValue(item, null) as string, "key"));
return ciphered;
答案 1 :(得分:-1)
尝试使用像(T)(对象)这样的转换。实施例。
private T SomeFunction(T arg)
{
var cipher = new List<string>();
cipher.Add("Test");
cipher.Add("Test 2");
cipher.Add("Test 3");
return (T)(Object)cipher;
}
示例
class Test<T> where T: IEnumerable<string>, ICollection<string>
{
public T Copy(T src)
{
List<string> result = new List<string>();
foreach (var s in src as ICollection<string>)
result.Add(s);
return (T)(Object)result;
}
public void Print(T what)
{
foreach (var s in what as ICollection<string>)
Console.WriteLine(s);
}
}
////////////////////////////////////////
Test<List<string>> t = new Test<List<string>>();
t.Print(t.Copy(new List<string>() { "One", "Two" }));