✅ How to change of property without setter?
I have
ObjectCollection
with different objects: TableCell
, TextObject
etc.
What I want: find TableCell, TextObject adn change their font family name.
I did following:
my code change full font now but I don't need this because I don't wanna change original font size!
I can do smth like this.. ((reportObjects[i] as TableCell)! ).Font.Name = ..
but Name
is doesn't have any setter.
So what to do? I wanna change only font name26 Replies
Font.Name isn't something you can change, you need to change the entire font instance
even if managed to change it, it wouldn't result in a new font - just that you changed the displayname of the current font
Does reflection work if theres no setter?
Doesn't matter, wont change the font
I think you're looking for how to retrieve the current font size and return that, regardless of the font name
Was just curious 😛
he wants to change the font
Right. If the name changes and he uses the previous font size, he solves his problem
he's instantiating a new font class which will look for any installed font matching that name
No,
Font
doesnt magically change if you use reflection to edit the name field
new Font("Your wanted font", oldFont.Size);
should do what you wantSorry, different contexts
Also if something is protected or private, there is a reason. Don't abuse reflection to tamper with things in ways that are explicitly discouraged
i swapped over to trying to help and the reflection would be a side discussion
I tried this:
var fontField = typeof(FontFamily).GetField(
"<Name>k__BackingField",
BindingFlags.Instance | BindingFlags.Public);
but fontField is always null
ah yes
thx for helping
it works!
it works!
as long as reportObjects[i] is never null
otherwise i think it'll be zero
you could get around that by checking for null, instead of using
!
to force the compiler to ignore itOne other thing id say would be to maybe try using a foreach. If you need the index, you could try something to the effect of
reportObjects.Select((s,i) => new KeyValuePair<int,obj>(i,s))
an anon object works as well... just couldn' remember the syntaxok, thanks, I wil try it
it will be TableCell or TextObject
btw, don't forget that you can assign in the pattern match
if (reportObjects[i] is TableCell tableCell)
Probably my favorite new(ish) addition to C#
out bool something
pattern matching is amazing.
i meant the assignment of the variable in the output
i absolutely hated having to declare the variable prior to because it really messed up loops and stuff and made you rethink things
ah yeah
out var
is greatsmth like that?
looks good I think
give it a try
it works
thanks
$close
Use the
/close
command to mark a forum thread as answered