如何在构造函数调用中分配类属性而不作为参数传递

huangapple go评论78阅读模式
英文:

How is class property assigned in constructor call without being a parameter

问题

我不太理解这种调用的魔法,尤其是第二个参数:

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]

DllImport的构造函数使用了两个参数,但查看.NET源代码浏览器中的代码,似乎只存在一个构造函数,只有第一个参数(dllName):

Class DllImportAttribute

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

huangapple
  • 本文由 发表于 2023年6月15日 14:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定