我需要以下方面的帮助:
我正在尝试设计一个API。以下是创建合同的两种方法:
方法1:
public class MyController
{
public void MyAction1(Dictionary<string, dynamic> input)
{
//Use input like below
//Read from input dictionary and apply minimal business logic if needed
//And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
}
public void MyAction2(Dictionary<string, dynamic> input)
{
//Use input like below
//Read from input dictionary and apply minimal business logic if needed
//And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
}
}在这种情况下,我们根本不需要数据契约。
办法2:
public class MyController
{
public void MyAction1(MyContractBusinessObject1 input)
{
//Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
}
public void MyAction2(MyContractBusinessObject2 input)
{
//Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
}
}在这种情况下,我们将有不同的业务类作为契约,用于不同的操作输入。请您建议上述哪一种方法更好,为什么?
让我举一个例子。假设我的操作正在进行登录和创建新帐户。在第一种情况下,输入将是
new Dictionary<string, dynamic>{{"Name","myname"},{"Passowrd",'mypassword'}}和
new Dictionary<string, dynamic>{{"Name","myname"},{"Passowrd",'mypassword'},{"Age",myage},{"otherInfo",myotherinfo}}但是在方法2中,输入将是
class Login{
public string Name{get; set;}
public string Password{get; set;}
} 和
class NewAccount{
public string Name{get; set;}
public string Password{get; set;}
public int Age{get; set;}
public OtherInfo OtherInfo{get; set;}
}发布于 2015-06-18 18:37:11
我将在这里假设以下几点:
如果我的假设是正确的,那么我会向以下方面提出一些建议。
public class Contact
{
public String FirstName { get; set; }
public String LastName { get; set; }
}
public class SpecialContact : Contact
{
public String Title { get; set; }
}
public class AnotherSpecialContact : Contact
{
public String Phone { get; set; }
}
public class ContactController
{
public void MyAction(Contact contact)
{
// VALIDATE: Example validation provided.
if (String.IsNullOrWhiteSpace(contact.FirstName)) { return; }
if (String.IsNullOrWhiteSpace(contact.LastName)) { return; }
if (contact is SpecialContact)
{
SpecialContact specialContact = contact as SpecialContact;
// Do things SpecialContact specific.
}
else if (contact is AnotherSpecialContact)
{
AnotherSpecialContact anotherSpecialContact = contact as AnotherSpecialContact;
// Do things AnotherSpecialContact specific.
}
// Do things Contact specific.
}
}我提出建议的理由:
SpecialContact和AnotherSpecialContact示例中看到的那样,您可以扩展操作以处理存在额外数据的特殊情况。如果存在数据较少的情况,则意味着您有错误的基类(即本场景中的Contact )。dynamic来反对呢?唯一一次我发现动态特别有用的是在反射的情况下,任何其他的时候,我发现它是相同的或更多的工作作为替代。如果您认为您需要dynamic,那么首先尝试一下Object。https://softwareengineering.stackexchange.com/questions/287216
复制相似问题