Can a C # property ever have GetMethod without SetMethod

Looking through the source code of the .NET kernel for System.Linq.Expressions, I found the following code located here :

MethodInfo mi = property.GetGetMethod(true);
if (mi == null)
{
    mi = property.GetSetMethod(true);
    if (mi == null)
    {
        throw Error.PropertyDoesNotHaveAccessor(property, nameof(property));
    }
}

Is there any way that GetGetMethod u GetSetMethod can return null, as it seems, is taken into account here? Is this dead code? The C # compiler does not allow the property to have no getter and no setter, as this is possible for PropertyInfo.

My motivation is to contribute to the OSS code by adding test coverage, so I'm trying to figure out which test cases this will cover

+4
source share
3 answers

CLI,

CLS 28: . §I.10.4. SpecialName, 24 CLS, . , .

. 52 PDF.

, .

, . , .

, , . .NET , . , .

, , "" , , .

+2

IL:

.class public C
{
  .property int32 Count() { } 
}

:

var prop = typeof(C).GetProperty("Count", BindingFlags.NonPublic | BindingFlags.Instance);

Expression.Property(null, prop);

:

ArgumentException: Int32 Count 'get' 'set'

+4

, System.Reflection.Emit

AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Module");

TypeBuilder type = module.DefineType("Type");
PropertyBuilder property = type.DefineProperty("Property", PropertyAttributes.None, typeof(void), new Type[0]);

Type createdType = type.CreateType();
PropertyInfo createdProperty = createdType.GetTypeInfo().DeclaredProperties.First();

Console.WriteLine(createdProperty.GetGetMethod(true) == null);
Console.WriteLine(createdProperty.GetSetMethod(true) == null);

, , IL

+2

Source: https://habr.com/ru/post/1651608/


All Articles