2014-02-06 219 views
1

我想寫一個類,它爲任何給定的域模型提供解密值。以下邏輯正常工作,但不知道要在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; 
} 

回答

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

我確實有異常處理機制,但是對於這個問題,我已經刪除了這個部分。 @John Saunders – Yass

+0

然後,只需從您發佈的代碼中刪除try/catch。你混淆了這個問題。 –

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);