我同时使用C++和C#,我想到的是,是否可以在C#中使用泛型来消除接口上的虚函数调用.考虑以下:
int Foo1(IList<int> list)
{
int sum = 0;
for(int i = 0; i < list.Count; ++i)
sum += list[i];
return sum;
}
int Foo2<T>(T list) where T : IList<int>
{
int sum = 0;
for(int i = 0; i < list.Count; ++i)
sum += list[i];
return sum;
}
/*...*/
var l = new List<int>();
Foo1(l);
Foo2(l);
Run Code Online (Sandbox Code Playgroud)
在Foo1内部,每次访问list.Count和list [i]都会导致虚函数调用.如果这是使用模板的C++,那么在调用Foo2时,编译器将能够看到虚拟函数调用可以被省略和内联,因为具体类型在模板实例化时已知.
但这同样适用于C#和泛型吗?当你调用Foo2(l)时,在编译时就知道T是List,因此list.Count和list [i]不需要涉及虚函数调用.首先,这是一个有效的优化,并没有可怕的破坏?如果是这样,编译器/ JIT是否足够聪明以进行此优化?
我有一个TextBlock和一个Rectangle,它们都位于一个空的WPF4窗口中.TextBlock的Foreground和Rectangle的Fill都设置为值为#80800000的SolidColorBrush.
这就是它的样子:

Rectangle的颜色是正确的(50%透明栗色),但TextBlock呈现平坦的灰色.这是怎么回事?
编辑:这是XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Foreground="#80800000" Height="100" HorizontalAlignment="Left" Margin="47,39,0,0" Text="TextBlock" VerticalAlignment="Top" Width="266" FontFamily="Arial" FontWeight="Bold" FontSize="56" />
<Rectangle Fill="#80800000" Height="100" HorizontalAlignment="Left" Margin="71,174,0,0" Stroke="{x:Null}" VerticalAlignment="Top" Width="200" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)