Don't enumerate fields on generic type Def (#77)

* Don't enumerate fields on generic type Def

Prevent exception being thrown when generic type definition is not a constructed generic type when trying to retrieve field values.

Added TODO with suggestion as to how to diagnose type arguments for generic type definition to create a constructed generic type.

* add test demonstrating error
This commit is contained in:
Tyler Young 2018-11-11 19:10:22 -05:00 committed by Ben Adams
parent c3519f14c5
commit aa10921687
2 changed files with 59 additions and 10 deletions

View File

@ -136,19 +136,26 @@ namespace System.Diagnostics
{
if (methodName == ".cctor")
{
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var field in fields)
if (type.IsGenericTypeDefinition && !type.IsConstructedGenericType)
{
var value = field.GetValue(field);
if (value is Delegate d)
// TODO: diagnose type's generic type arguments from frame's "this" or something
}
else
{
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var field in fields)
{
if (ReferenceEquals(d.Method, originMethod) &&
d.Target.ToString() == originMethod.DeclaringType.ToString())
var value = field.GetValue(field);
if (value is Delegate d)
{
methodDisplayInfo.Name = field.Name;
methodDisplayInfo.IsLambda = false;
method = originMethod;
break;
if (ReferenceEquals(d.Method, originMethod) &&
d.Target.ToString() == originMethod.DeclaringType.ToString())
{
methodDisplayInfo.Name = field.Name;
methodDisplayInfo.IsLambda = false;
method = originMethod;
break;
}
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
namespace Ben.Demystifier.Test
{
public class GenericMethodDisplayStringTests
{
private static class Example<T>
{
// ReSharper disable once StaticMemberInGenericType
public static readonly StackFrame StackFrame;
static Example()
{
var fun = new Func<StackFrame>(() => new StackFrame(0, true));
StackFrame = fun();
}
}
[Fact]
public void DiagnosesGenericMethodDisplayString()
{
var sf = Example<Type>.StackFrame;
try
{
var s = EnhancedStackTrace.GetMethodDisplayString(sf.GetMethod());
Assert.True(true, "Does not throw exception when diagnosing generic method display string.");
}
catch (Exception ioe)
{
Assert.True(false, "Must not throw an exception when diagnosing generic method display string.");
}
}
}
}