在大型项目中使用哪个更好,为什么更好:
#if DEBUG
public void SetPrivateValue(int value)
{ ... }
#endif
Run Code Online (Sandbox Code Playgroud)
要么
[System.Diagnostics.Conditional("DEBUG")]
public void SetPrivateValue(int value)
{ ... }
Run Code Online (Sandbox Code Playgroud) 您遇到的最糟糕的 现实世界宏/预处理器滥用是什么(请不要设想IOCCC答案*哈哈*)?
如果它真的很有趣,请添加一个简短的片段或故事.目标是教一些东西,而不是总是告诉人们"永远不要使用宏".
ps:之前我曾经使用过宏...但是当我有一个"真正的"解决方案时,我最终会摆脱它们(即使真正的解决方案是内联的,它也会变得类似于宏).
额外:举一个例子,宏实际上比非宏解决方案更好.
相关问题: C++宏什么时候有用?
从C++ 11开始,人们可以写出类似的内容
#include <vector>
#include <string>
struct S
{
S(int x, const std::string& s)
: x(x)
, s(s)
{
}
int x;
std::string s;
};
// ...
std::vector<S> v;
// add new object to the vector v
// only parameters of added object's constructor are passed to the function
v.emplace_back(1, "t");
Run Code Online (Sandbox Code Playgroud)
是否有的C++函数任何C#类似物像emplace
或emplace_back
容器类(System.Collections.Generic.List
)?
更新:
在C#中,类似的代码可能会被编写为list.EmplaceBack(1, "t");
代替list.Add(new S(1, "t"));
.不记得班级名称并且new ClassName
每次都在这种情况下写作会很好.
我有一个类是这样的类:
public class Abc
{
public string City
{
get { return _getValue(); }
set { _setValue(value); }
}
public string State
{
get { return _getValue(); }
set { _setValue(value); }
}
private string _getValue()
{
// determine return value via StackTrace and reflection
}
...
}
Run Code Online (Sandbox Code Playgroud)
(是的,我知道StackTrace /反射很慢;不要惹我生气)
鉴于所有属性都被声明为相同,我能够做的就是有一些简单/干净的方式来声明它们,而不需要反复复制相同的get/set代码.
我需要所有属性的Intellisense,这排除了使用例如.ExpandoObject
.
如果我在C/C++的土地上,我可以使用一个宏,例如:
#define DEFPROP(name) \
public string name \
{ \
get { return _getValue(); } \
set { _setValue(value); } \
} \
Run Code Online (Sandbox Code Playgroud)
然后: …
c# ×3
preprocessor ×2
c ×1
c++ ×1
collections ×1
debugging ×1
emplace ×1
macros ×1
properties ×1