ConfigurationElement.IsModified Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
При реализации в производном классе указывает, был ли изменен данный элемент конфигурации с момента последнего сохранения или загрузки.
protected:
virtual bool IsModified();
protected public:
virtual bool IsModified();
protected virtual bool IsModified ();
protected internal virtual bool IsModified ();
abstract member IsModified : unit -> bool
override this.IsModified : unit -> bool
Protected Overridable Function IsModified () As Boolean
Protected Friend Overridable Function IsModified () As Boolean
Возвращаемое значение
Значение true
, если элемент был изменен; в противном случае — значение false
.
Примеры
В следующем примере показано, как расширить .IsModified
protected override bool IsModified()
{
bool ret = base.IsModified();
// You can enter your custom processing code here.
return ret;
}
Protected Overrides Function IsModified() As Boolean
Dim ret As Boolean = MyBase.IsModified()
' Enter your custom processing code here.
Return ret
End Function 'IsModified
End Class
Метод, показанный в предыдущем примере, вызывается при изменении элемента конфигурации, как показано в следующем примере.
// Show how to use IsModified.
// This method modifies the port property
// of the url element named Microsoft and
// saves the modification to the configuration
// file. This in turn will cause the overriden
// UrlConfigElement.IsModified() mathod to be called.
static void ModifyElement()
{
try
{
// Get the configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Get the MyUrls section.
UrlsSection myUrlsSection =
config.GetSection("MyUrls") as UrlsSection;
UrlsCollection elements = myUrlsSection.Urls;
IEnumerator elemEnum =
elements.GetEnumerator();
int i = 0;
while (elemEnum.MoveNext())
{
if (elements[i].Name == "Microsoft")
{
elements[i].Port = 1010;
bool readOnly = elements[i].IsReadOnly();
break;
}
i += 1;
}
if (!myUrlsSection.ElementInformation.IsLocked)
{
config.Save(ConfigurationSaveMode.Full);
// This to obsolete the MyUrls cached
// section and read the updated version
// from the configuration file.
ConfigurationManager.RefreshSection("MyUrls");
}
else
Console.WriteLine(
"Section was locked, could not update.");
}
catch (ConfigurationErrorsException err)
{
Console.WriteLine("[ModifyElement: {0}]",
err.ToString());
}
}
' Show how to use IsModified.
' This method modifies the port property
' of the url element named Microsoft and
' saves the modification to the configuration
' file. This in turn will cause the overriden
' UrlConfigElement.IsModified() mathod to be called.
Shared Sub ModifyElement()
Try
' Get the current configuration file.
Dim config _
As System.Configuration.Configuration = _
ConfigurationManager.OpenExeConfiguration( _
ConfigurationUserLevel.None)
' Get the MyUrls section.
Dim myUrlsSection As UrlsSection = _
config.GetSection("MyUrls")
Dim elements As UrlsCollection = _
myUrlsSection.Urls
Dim elemEnum As IEnumerator = _
elements.GetEnumerator()
Dim i As Integer = 0
While elemEnum.MoveNext()
If elements(i).Name = "Microsoft" Then
elements(i).Port = 1010
Dim [readOnly] As Boolean = _
elements(i).IsReadOnly()
Exit While
End If
i += 1
End While
If Not myUrlsSection.ElementInformation.IsLocked Then
config.Save(ConfigurationSaveMode.Full)
' This to obsolete the MyUrls cached
' section and read the updated version
' from the configuration file.
ConfigurationManager.RefreshSection("MyUrls")
Else
Console.WriteLine("Section was locked, could not update.")
End If
Catch err As ConfigurationErrorsException
Console.WriteLine("[ModifyElement: {0}]", _
err.ToString())
End Try
End Sub
Комментарии
Метод IsModified определяет, будет ли этот ConfigurationElement объект записан в файл конфигурации при вызове Save метода . Если возвращаемое значение — false
, предполагается, что файл конфигурации представляет текущее значение элемента.
По умолчанию IsModified возвращает значение true
после установки свойства для данного ConfigurationElement объекта с помощью индексатора.
Переопределите IsModified метод для предоставления пользовательского указания состояния этого ConfigurationElement элемента.
Применяется к
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по