关于c#中的upcast,我有一个简单的问题.例如,我有两个接口:
interface IUSer
{
string UserName { get; set; }
}
interface IAdmin: IUSer
{
string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
...以及实现IAdmin接口的类:
class Admin : IAdmin
{
public string Password { get; set; }
public string UserName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我创建一个Admin类型的对象并尝试将其向上转换为IUser时,从技术上讲,我只能访问UserName user.UserName:
var admin = new Admin() { UserName = "Arthur", Password = "hello" };
var user = (IUSer)admin;
Console.WriteLine( user.UserName );
Run Code Online (Sandbox Code Playgroud)
...但是如果我使用Reflection循环遍历此对象的属性,就像这样:
private static void Outputter(IUSer user)
{
foreach (var prop in user.GetType().GetProperties())
{
Console.WriteLine(prop.Name + …Run Code Online (Sandbox Code Playgroud) 我有一个简单的Web应用程序,在客户端具有angular,在服务器端具有asp.net核心web-api。我使用InMemoryDatabase
services.AddDbContext<ItemsContext>(options => options.UseInMemoryDatabase("ItemsDB"));
Run Code Online (Sandbox Code Playgroud)
存储数据以简化开发。但是我遇到了一个问题。我在web-api上有一个控制器来响应用户的请求:
[Route("api/[controller]")]
public class ItemsController : Controller
{
private readonly IApiService apiService;
public ItemsController(IApiService apiService)//using DI from Startup.cs
{
this.apiService = apiService;
}
[HttpPost, Route("addItem")]
public async Task<Response> Add([FromBody]Item item)
{
return await apiService.Add(item);
}
[HttpDelete("{id}")]
public async Task<Response> Delete(int id)
{
return await apiService.Delete(id);
}
[HttpPut]
public async Task<Response> Put([FromBody]Item item)
{
return await apiService.Put(item);
}
}
Run Code Online (Sandbox Code Playgroud)
以及以下Startup.cs配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ItemsContext>(options => options.UseInMemoryDatabase("ItemsDB"));
services.AddSingleton<IUnitOfWork, UnitOfWork>(provider => {
var context = services.BuildServiceProvider().GetService<ItemsContext>(); …Run Code Online (Sandbox Code Playgroud)