通用退货类型

时间:2014-02-06 06:06:35

标签: c# generics

我想编写一个类,它为任何给定的域模型提供解密值。以下逻辑工作正常,但不知道在XXXXXX的位置声明什么。

示例域模型:

public class emp
{
    public string empname{get;set;}
}

我会将DecryptByObject方法称为:

var x = DecryptByObject(emp,KEY);

DecryptByObject方法:

public XXXXX DecryptByObject(XXXXXX myObject, string decryptKey)
{
    Type t = myObject.GetType();       

    foreach (MemberInfo mi in t.GetMembers())
    {
        try
        {
            if (mi.MemberType == MemberTypes.Property)
            {
                string value = ((PropertyInfo)mi).GetValue(myObject).ToString();
                var bytes = Convert.FromBase64String(value);
                var decryValue = MachineKey.Unprotect(bytes, decryptKey);
                ((PropertyInfo)mi).SetValue(myObject, Encoding.UTF8.GetString(decryValue));
            }
        }
        catch (Exception ex) { }
    }

    return myObject;
}

2 个答案:

答案 0 :(得分:1)

您应该使用如下所示。

public T DecryptByObject<T>(T myObject, string decryptKey)
{
    Type t = myObject.GetType();
    PropertyInfo prop = t.GetProperty("Items");
    object list = prop.GetValue(myObject);

    foreach (MemberInfo mi in t.GetMembers())
    {
        try
        {
            if (mi.MemberType == MemberTypes.Property)
            {
                string value = ((PropertyInfo)mi).GetValue(myObject).ToString();
                var bytes = Convert.FromBase64String(value);
                var decryValue = MachineKey.Unprotect(bytes, decryptKey);
                ((FieldInfo)mi).SetValue(myObject, Encoding.UTF8.GetString(decryValue));
            }
        }
        catch (Exception ex) { }
    }


    return myObject;
}

答案 1 :(得分:0)

试试这个:

public T DecryptByObject<T>(T myObject, string decryptKey)

作为一个侧面点,您想在此处添加一些错误检查,因为prop可能是null或者可能会引发错误:

Type t = myObject.GetType();
PropertyInfo prop = t.GetProperty("Items");
if (prop == null)
{
    // handle this error...
}

object list = prop.GetValue(myObject);