英文:
How is class property assigned in constructor call without being a parameter
问题
我不太理解这种调用的魔法,尤其是第二个参数:
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
DllImport的构造函数使用了两个参数,但查看.NET源代码浏览器中的代码,似乎只存在一个构造函数,只有第一个参数(dllName):
CharSet
是 DllImportAttribute 类的一个属性,所以,如何能在构造函数调用期间使用赋值操作直接进行赋值呢?即使这个类提供了带有 CharSet
作为第二个参数的构造函数,像这样的赋值操作对我来说也不太熟悉。
如果我有一个命名为 CharSet
的局部或全局变量在外部范围,我可以将值 CharSet.Auto
分配给该变量,然后将其作为参数传递给构造函数(在一个操作中分配和传递),就像这样:
CharSet CharSet;
DllImport("Kernel32.dll", CharSet = CharSet.Auto)
但是 CharSet
是 DllImportAttribute 中的一个属性,所以这让我感到有些困惑。有什么想法吗?背后发生了什么?
英文:
I don't get behind the magic of these kind of calls, especially the second argument:
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
The constructor of DllImport is called with two parameters, but looking at the code at .NET source browser, it seems to only exist a constructor with the first parameter (`dllName'):
Class DllImportAttribute
CharSet
is a property of the DllImportAttribute class, so, how can it be assigned directly during the constructor call with an assignment operation? Even if the class would offer two parameters with CharSet
being the second, an assignment operation like that is not known to me.
If I would have a local or global variable at outer scope being named CharSet
, I could assign the value CharSet.Auto
to that variable and pass it as an argument to the constructor (assigned and passed in one), like this:
CharSet CharSet;
DllImport("Kernel32.dll", CharSet = CharSet.Auto)
But CharSet is a property within DllImportAttribute, so this kind of puzzles me. Any ideas? What is happening behind the scenes?
答案1
得分: 1
Positional parameters correspond to the parameters of the attribute constructor. Named or optional parameters correspond to either properties or fields of the attribute. - microsoft docs
英文:
> Positional parameters correspond to the parameters of the attribute constructor. Named or optional parameters correspond to either properties or fields of the attribute. - microsoft docs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论