在c#中创建新的属性类型泛型T

时间:2015-02-17 09:55:43

标签: c# generics

我有这样的函数,它得到一个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是具有一些属性的类定义

2 个答案:

答案 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" }));