我正在尝试学习C#。我掌握了基本语法,但试图找出以下代码的细目:
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
我知道,在一个基本函数中,有函数名,并且打开/关闭花括号-ex。 function_name(参数); 。但是,在上面的行中,我所假设的是一堂课。
有人可以向我解释这句话
答案 0 :(得分:2)
这2行实际上应该只是其中的一行。 serviceProvider之前的(IPluginExecutionContext)将结果从GetService投射到IPluginExecutionContext。
此处有更多信息:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
答案 1 :(得分:1)
我假设您是在
开头引用(IPluginExecutionContext)
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
这是GetService
返回类型为IPluginExecutionContext
的对象的explicit cast。
答案 2 :(得分:1)
如果您将其读为一行
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
您将能够看到它正在将ServiceProvider对象中的GetService()方法调用的结果显式转换为IPluginExecutionContext类型。
GetService()方法可能有重载,您可以在其中重载不同类型的上下文
用于转换和类型转换的Microsoft文档: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
答案 3 :(得分:1)
首先,我们可以缩短名称并看到实际上这是一行:
// Obtain the execution context from the service provider.
ISomeInterface c = (ISomeInterface) serviceProvider.GetService(typeof(ISomeInterface));
关于含义,此行通过向接口{{的当前注册对象}询问c
(类似于依赖性注入容器)来创建类型ISomeInterface
的变量serviceProvider
。 1}}。
代码很丑陋,因为ISomeInterface
没有提供类型化的api。其他服务提供商提供了更好的api,例如:
serviceProvider
带有列表的示例。
让我们想象一下,我们有ISomeInterface c = serviceProvider.GetService<ISomeInterface>();
个对象的列表
AwesomeClass
由于某种原因,列表将对象存储为public class AwesomeClass: ISomeInterface
该代码需要强制转换。
object
如果正确键入列表,则代码会更好:
var list = new List<object>();
list.Add(new AwesomeClass(());
ISomeInterace c = (ISomeInterface) list[0];
or
AwesomeClass c = (AwesomeClass ) list[0];