相关疑难解决方法(0)

是否可以访问自动实现属性背后的支持字段?

我知道我可以使用详细的属性语法:

private string _postalCode;

public string PostalCode
{
    get { return _postalCode; }
    set { _postalCode = value; }
}
Run Code Online (Sandbox Code Playgroud)

或者我可以使用自动实现的属性.

public string PostalCode { get; set; }
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式访问​​自动实现属性后面的支持字段吗?(在这个例子中,它将是_ postalCode).


编辑:我的问题不是关于设计,而是关于,比方说,理论能力.

c#

55
推荐指数
5
解决办法
2万
查看次数

是否有可能通过反思得到一个房产的私人制定者?

我编写了一个自定义序列化程序,通过反射设置对象属性.可序列化类用serializable属性标记,所有可序列化属性也被标记.例如,以下类是可序列化的:

[Serializable]
public class Foo
{
   [SerializableProperty]
   public string SomethingSerializable {get; set;}

   public string SometthingNotSerializable {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

当系列化程序被要求反序列化时SomethingSerializable,它获取属性的set方法并使用它来设置它,如下所示:

PropertyInfo propertyInfo; //the property info of the property to set
//...//
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
   propertyInfo.GetSetMethod().Invoke(obj, new object[]{val});
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但是,如何才能使属性设置器只对序列化器可访问?如果setter是私有的:

public string SomethingSerializable {get; private set;}
Run Code Online (Sandbox Code Playgroud)

然后调用propertyInfo.GetSetMethod()在序列化器中返回null.有没有办法访问私有setter或任何其他方式,以确保只有序列化程序可以访问setter?不保证序列化程序在同一个程序集中.

c# reflection serialization

22
推荐指数
1
解决办法
1万
查看次数

如何在.NET Core中更改/创建依赖于域的自定义FileProvider(即,一个提供多种站点呈现逻辑的Web应用程序)

我目前正在使用.NET Core创建一个多租户Web应用程序。并面临一个问题:

1)Web App 基于一组域名提供不同的视图逻辑

2)视图是MVC视图,并存储在Azure Blob存储中

3)多个站点共享相同的.NET Core MVC控制器,因此只有Razor视图在小的逻辑上是不同的。

问题...。A)可能吗?我创建了一个MiddleWare来进行操作,但是由于文件提供者应依赖于域,因此无法在上下文级别正确分配文件提供者。

B)或者,除了思考和尝试通过FileProvider之外,还有其他方法可以实现我想要实现的目标吗?

非常感谢!!!

.net asp.net-core-mvc .net-core asp.net-core

5
推荐指数
1
解决办法
1233
查看次数

访问propertyinfo中的属性

我需要通过Tag类在BFrame类中设置Value属性.

我怎么设置Value房产?

澄清:
我不是试图在类中设置Frame属性的值,Tag而是设置Value属性Frame类型的属性BFrame.

class BFrame
{
    string Value{get; set;}
}

class Tag
{
    BFrame Frame{get;}
}

public void func(Tag tag, string newValue)
{
    PropertyInfo frameProperty = tag.GetType().GetProperty("Frame");
    var oldValue = frameProperty.GetValue(tag);
    //frameProperty.SetValue(tag, newValue); //Doesn't work. Throws exception because there is no setter
    //TODO: Set the Value property inside the BFrame class
    //Somethig like this: tag.Frame.Value = newValue;
}
Run Code Online (Sandbox Code Playgroud)

.net c# reflection

2
推荐指数
1
解决办法
74
查看次数