简体   繁体   中英

C# Specialise instance of a class

I have a problem which i've been googling but can't find the answer to.

Say if you have a class called Account which inherits from a class called AccountInquiry.

If you have an instance of AccountInquiry, can you convert this into an instance of Account without effectively copying it. If not what is the best way to manage this.

Basically a bit of background, when someone fills in a basic Name/Email form on our website is creates an account inquiry, once they've done this they are presented with a 2nd form. If this 2nd form gets fills in the account inquiry is converted into an account.

Many thanks

Sam

It doesn't sound like an Account really is an AccountInquiry . It sounds much more like these should be two entirely separate classes, even if they have some of the same properties.

Be careful before you use inheritance - consider whether it's really appropriate or not.

In this case your AccountInquiry sounds like it's effectively search criteria for a real Account - so you should probably have some service class which is able to perform the query, with a method something like:

List<Account> FindAccounts(AccountInquiry inquiry)

Or possibly just a return type of Account if only a single account should be matched. There's no "conversion" going on here - you'd just be using the properties of one object to find another.

(I suspect it should really be enquiry rather than inquiry by the way, but that's an aside.)

You can only up-cast if the original class (Account) is a down-cast from AccountInquiry so, no, that's not possible.

Copying is the only option.

can you convert this into an instance of Account without effectively copying it

In this scenario, no. Account can be cast down to AccountInquiry but not vice versa. You could use a tool like AutoMapper to make it easier to map fields across though.

As an alternative approach what you could do is make Account a property of AccountInquiry which would remove the problem altogether.

You can't, but ¿What about this?

Account account = new Account();

account.CustomerID = 25;

account.MaxAmount = (decimal)5000.00;

And then

((AccountInquiry)account).Method = "ListChanges";
((AccountInquiry)account).StartDate = DateTime.Today.AddDays(-10);
((AccountInquiry)account).EndDate = DateTime.Today;

Then if you need pass to any method that his parameter should be Type you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM