How can I provide property-level string formatting?
Not sure if the question wording is accurate, but here's what I want to do: I want to databind a class with some strings in it:
class MyClass
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
When databinding, everything behaves normally. On the back end, I'm writing to a file and I want MyProperty2 to always be encrypted using some encryption algorithm. I want my back-end code to write each string without needing to know that encryption is required (I want the class to know it should be encrypted, not the consumer). Can I do this with a type converter, or something similar?
EDIT: There are other scenarios as well. Some booleans I want to format as "Y" or "N", other booleans I want formatted as "Enabled" / "Disabled", etc. I can write (and have written) helper methods and let the file writer call the helper methods as appropriate, I'm just wondering if there's a way to 开发者_如何学编程do this without the file writer needing to know which objects need which kind of formatting and let the objects tell that to the file writer.
I'm not sure exactly what you're trying to achieve, but you could use a private backing field that is encrypted, then decrypt/encrypt in the property settor. When writing to the file, write the backing field, not the property.
private string encryptedProperty2;
public string MyProperty2
{
get { return this.Decrypt( this.encryptedProperty2 ); }
set { this.encryptedProperty2 = this.Encrypt( value ); }
}
private void Init()
{
...
this.encryptedProperty2 = ... read from file ...
...
}
public void Save()
{
...
writer.Write( this.encryptedProperty2 );
...
}
Alternatively, you could do the encryption at the time that you read/write to the file. If it's sensitive, though, you may want to keep it encrypted in memory.
You can create a private function
in MyClass
that does the encryption you want. Then in the Get method for MyProperty2
call the private function.
E.g.
public string MyProperty2
{
get { return DoEncrypt(myProperty2);}
set;
}
精彩评论