I have a parent class
public class User
{
public int UserKey { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
I also have the class below that inherits from User
public class MyInfo : User
{
public string Name { get; set; }
}
I have a utility class that returns a type of User
. However I want to use the same method for MyInfo
and only fill out whatever MyInfo
inherited from User
. The method can be found below:
public static User fetchUserInformation()
{
User user = new User()
//fetch data..
return user;
}
What I’m doing is
MyInfo myinfo = fetchUserInformation();
but this wouldn’t work since fetchUserInformation
returns a type of User
.
You can try to serialize User
and deserialize it to MyInfo
.
Change
MyInfo myinfo = fetchUserInformation();
to
MyInfo myInfo = JsonConvert.DeserializeObject<MyInfo>(JsonConvert.SerializeObject(fetchUserInformation()));
Another way,you can try without using inheritance.Here is a demo:
public class MyInfo
{
public string name { get; set; }
public User user { get; set; }
}
MyInfo myInfo = new MyInfo { user = fetchUserInformation() };
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments